Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
Add Nota Consort, a paraphonic semi-modular synth
Egor Khindikaynenf8070671317e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 49db7e5b..aa960326 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,28 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.## [Unreleased]### Added+- **Nota Consort — a paraphonic semi-modular synth.** A new built-in instrument (kind 15) in+ the spirit of a four-oscillator paraphonic Moog. Four oscillators (triangle, saw, square or+ pulse with PWM; 32′–2′; oscillator 2 syncs to 1 and 4 to 3) feed a mixer with noise, drive+ and an EXT input that is normalled to the output for the classic feedback growl, then two+ ladder filters — HP→LP in series, or parallel stereo as LP/LP or HP/LP with a Spacing+ offset between them — and two ADSR envelopes. **MONO**, **DUO** and **PARA** share one+ filter and envelope pair the way a paraphonic synth does (each held note gets its own+ oscillators; Multi trig retriggers the envelopes; Unison doubles idle oscillators with a+ detune), and **True poly** gives 16 complete voices instead. Glide per oscillator — linear+ rate, linear time or exponential, optionally legato-only. An LFO with six shapes (free or+ tempo-synced) modulates pitch, cutoff and PWM, and a stereo **bucket-brigade delay** (darker+ as it gets longer, with compander, overload and ping-pong; or a clean digital line) sits at+ the end. A 16-step **sequencer / arpeggiator** with ratchets, ties, rests, swing, forward /+ backward / random order and latch plays in time with the song. The **patch bay** takes up to+ 12 cables across 42 points — oscillator, filter, envelope, LFO, keyboard, sequencer and+ utility outputs into pitch, PWM, cutoff, resonance, VCA, delay and LFO-rate inputs, plus+ Gate, Filter, VCA and EXT inputs whose internal connection a cable replaces; feedback loops+ are allowed. Patch it as a matrix, as a strip of jacks inside the Patch tab, or on a+ full-card overlay with every point; drag from jack to jack to connect, ⌥-click to pull a+ cable. Cables are ordinary parameters, so patches are saved with the project and in presets,+ duplicate with the track, and their depths can be automated. 28 factory presets; a freeze+ matches playback exactly.- **Nota Prism — multiband dynamics.** A new built-in audio effect (kind 21) that splits thesignal into Low / Mid / High with phase-coherent crossovers — or two bands, or one — and giveseach band a compressor above a threshold and an expander (or an upward compressor, which liftsdiff --git a/FEATURES.md b/FEATURES.mdindex 31ff654a..c5ab9149 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -218,6 +218,13 @@ and user presets, automation, persistence and cloning.Poly/Unison/Mono, poly unison stacks, glide, the Release switch, and **Vintage Drift**(seeded per-voice spread — a render is identical for the same seed, so freezing isexact). 40 factory presets. Also builds as a standalone VST3 for other hosts.+- **Nota Consort** — paraphonic semi-modular synth: four oscillators (tri / saw / square /+ pulse, sync 2→1 and 4→3), a mixer with noise, drive and a feedback-normalled EXT input, dual+ ladder filters (HP→LP series, LP/LP or HP/LP parallel stereo with spacing), two ADSRs,+ MONO / DUO / PARA paraphony or 16-voice true poly, per-oscillator glide (LCR / LCT / EXP),+ a six-shape LFO, a stereo bucket-brigade delay, a 16-step sequencer / arpeggiator with+ ratchets and ties, and a 12-cable patch bay over 42 points (matrix, jack strip or full-card+ overlay). Cables are parameters: saved, preset-able and automatable. 28 factory presets.### Audio effects- **Nota EQ-8** (kind 0) — 8-band parametric.diff --git a/src/managed/Nota.App/Controls/ConsortViews.cs b/src/managed/Nota.App/Controls/ConsortViews.csnew file mode 100644index 00000000..18b631d4--- /dev/null+++ b/src/managed/Nota.App/Controls/ConsortViews.cs@@ -0,0 +1,740 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Custom-drawn views for the Nota Consort card: the patch-bay jack tables (mirroring the+// engine's jack indices), LFO shape glyphs, the dual-ladder response (drag = cutoff /+// resonance), the BBD tap display, the 16-step type strip, the step pitch lane, the jack+// field with its cables (drag jack → jack to patch, Alt-click to pull) and the source ×+// destination matrix. Values are pushed in by the card's refresh tick; edits come back as+// events so the card writes the params and brackets automation gestures.++using System;+using System.Collections.Generic;+using System.Globalization;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using Avalonia.Media;++namespace Nota.App;++// ---- patch-bay jacks (indices == the engine's consort::Src / consort::Dst — append only) ----+internal static class ConsortJacks+{+ public const int JackScale = 63;+ public enum Tone { Mod, Env, Audio }++ public readonly record struct Jack(bool Out, int Index, string Short, string Name, Tone Tone);++ // Sources (outputs), index 1..20.+ public static readonly Jack[] Sources =+ {+ new(true, 0, "", "—", Tone.Mod),+ new(true, 1, "out", "LFO out", Tone.Mod),+ new(true, 2, "1", "Env 1 out", Tone.Env),+ new(true, 3, "2", "Env 2 out", Tone.Env),+ new(true, 4, "1", "Osc 1 out", Tone.Audio),+ new(true, 5, "2", "Osc 2 out", Tone.Audio),+ new(true, 6, "3", "Osc 3 out", Tone.Audio),+ new(true, 7, "4", "Osc 4 out", Tone.Audio),+ new(true, 8, "n", "Noise out", Tone.Audio),+ new(true, 9, "out", "Filt out", Tone.Audio),+ new(true, 10, "pit", "Seq pitch", Tone.Audio),+ new(true, 11, "gt", "Seq gate", Tone.Audio),+ new(true, 12, "clk", "Clock out", Tone.Audio),+ new(true, 13, "pit", "Kbd pitch", Tone.Mod),+ new(true, 14, "gt", "Kbd gate", Tone.Mod),+ new(true, 15, "vel", "Velocity", Tone.Mod),+ new(true, 16, "at", "Aftertouch", Tone.Mod),+ new(true, 17, "wh", "Mod wheel", Tone.Mod),+ new(true, 18, "a1›", "Atten 1 out", Tone.Mod),+ new(true, 19, "a2›", "Atten 2 out", Tone.Mod),+ new(true, 20, "Σ›", "Sum out", Tone.Mod),+ };+ // Destinations (inputs), index 1..22.+ public static readonly Jack[] Dests =+ {+ new(false, 0, "", "—", Tone.Mod),+ new(false, 1, "rate", "LFO rate", Tone.Mod),+ new(false, 2, "g1", "Gate 1 in", Tone.Mod),+ new(false, 3, "g2", "Gate 2 in", Tone.Mod),+ new(false, 4, "p", "Osc pitch", Tone.Mod),+ new(false, 5, "p1", "Osc 1 pitch", Tone.Mod),+ new(false, 6, "p2", "Osc 2 pitch", Tone.Mod),+ new(false, 7, "p3", "Osc 3 pitch", Tone.Mod),+ new(false, 8, "p4", "Osc 4 pitch", Tone.Mod),+ new(false, 9, "pw", "Osc PWM 1–4", Tone.Mod),+ new(false, 10, "c1", "Filt 1 cutoff", Tone.Mod),+ new(false, 11, "c2", "Filt 2 cutoff", Tone.Mod),+ new(false, 12, "res", "Filt res", Tone.Mod),+ new(false, 13, "in", "Filt in", Tone.Mod),+ new(false, 14, "cv", "VCA CV", Tone.Mod),+ new(false, 15, "in", "VCA in", Tone.Mod),+ new(false, 16, "tim", "Delay time", Tone.Mod),+ new(false, 17, "fb", "Delay feedback", Tone.Mod),+ new(false, 18, "mix", "Delay mix", Tone.Mod),+ new(false, 19, "ext", "Ext in", Tone.Mod),+ new(false, 20, "a1", "Atten 1 in", Tone.Mod),+ new(false, 21, "a2", "Atten 2 in", Tone.Mod),+ new(false, 22, "Σ", "Sum in", Tone.Mod),+ };+ // Inputs whose internal normal a cable breaks.+ public static readonly HashSet<int> Normalled = new() { 2, 3, 13, 15, 19 };+ public static int Points => Sources.Length - 1 + Dests.Length - 1;++ public static IBrush ToneBrush(Tone t) => t switch { Tone.Env => NotaPalette.Teal, Tone.Audio => NotaPalette.Accent, _ => ChamberInk.Mauve };+ public static Color ToneColor(Tone t) => t switch { Tone.Env => Color.Parse("#5B9E9C"), Tone.Audio => NotaPalette.AccentColor, _ => ChamberInk.MauveColor };+ public static Jack Src(int i) => i > 0 && i < Sources.Length ? Sources[i] : Sources[0];+ public static Jack Dst(int i) => i > 0 && i < Dests.Length ? Dests[i] : Dests[0];+ public static string ShortName(string n) => n.Replace(" out", "").Replace(" in", "").Replace("Osc ", "Osc").Replace("Filt ", "Filt").Replace(" cutoff", "").Replace("Delay ", "Dly ").Replace(" pitch", "").Replace("Env ", "Env");+ public static int FromNorm(float v) => Math.Clamp((int)Math.Round(v * JackScale), 0, JackScale);+ public static float ToNorm(int i) => i / (float)JackScale;+}++// One cable as the views see it: slot index, source, destination, depth −1..1.+internal readonly record struct ConsortCable(int Slot, int Src, int Dst, float Depth);++// ---- LFO shape glyphs: 0 sine, 1 ramp up, 2 ramp down, 3 square, 4 S&H, 5 smooth random ----+internal sealed class ConsortLfoIcon : Control+{+ private readonly int _s;+ public IBrush Stroke { get; set; } = NotaPalette.TextTertiary;+ public ConsortLfoIcon(int shape, double w = 16, double h = 8) { _s = shape; Width = w; Height = h; }+ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width, h = Bounds.Height, t = 0.8, b = h - 0.8, m = h / 2;+ var g = new StreamGeometry();+ using (var c = g.Open())+ {+ switch (_s)+ {+ case 0:+ c.BeginFigure(new Point(0, m), false);+ for (int i = 1; i <= 24; i++) { double x = i / 24.0; c.LineTo(new Point(x * w, m - Math.Sin(x * Math.PI * 2) * (m - t))); }+ break;+ case 1:+ c.BeginFigure(new Point(0, b), false);+ c.LineTo(new Point(w * 0.48, t)); c.LineTo(new Point(w * 0.48, b)); c.LineTo(new Point(w * 0.96, t)); c.LineTo(new Point(w * 0.96, b));+ break;+ case 2:+ c.BeginFigure(new Point(0, t), false);+ c.LineTo(new Point(w * 0.48, b)); c.LineTo(new Point(w * 0.48, t)); c.LineTo(new Point(w * 0.96, b));+ break;+ case 3:+ c.BeginFigure(new Point(0, b), false);+ c.LineTo(new Point(0, t)); c.LineTo(new Point(w * 0.5, t)); c.LineTo(new Point(w * 0.5, b)); c.LineTo(new Point(w, b));+ break;+ case 4:+ double[] lv = { 0.6, 0.2, 0.8, 0.45 };+ c.BeginFigure(new Point(0, t + (b - t) * lv[0]), false);+ for (int i = 0; i < 4; i++)+ {+ double y = t + (b - t) * lv[i];+ c.LineTo(new Point(w * i / 4.0, y)); c.LineTo(new Point(w * (i + 1) / 4.0, y));+ }+ break;+ default:+ c.BeginFigure(new Point(0, b), false);+ double[] rv = { 0.9, 0.35, 0.7, 0.1, 0.5 };+ for (int i = 1; i <= 24; i++)+ {+ double x = i / 24.0 * 4; int k = Math.Min(3, (int)x); double f = x - k; f = 0.5 - 0.5 * Math.Cos(f * Math.PI);+ c.LineTo(new Point(i / 24.0 * w, t + (b - t) * (rv[k] + (rv[k + 1] - rv[k]) * f)));+ }+ break;+ }+ }+ ctx.DrawGeometry(null, new Pen(Stroke, 1.3, lineJoin: PenLineJoin.Round), g);+ }+}++// ---- small jack glyph (a status light on the panels: patched = filled in the cable colour) ----+internal sealed class ConsortJackDot : Control+{+ private IBrush? _fill;+ public ConsortJackDot(double d = 11) { Width = d; Height = d; }+ public void Set(IBrush? patched) { if (!ReferenceEquals(patched, _fill)) { _fill = patched; InvalidateVisual(); } }+ public override void Render(DrawingContext ctx)+ {+ double r = Math.Min(Bounds.Width, Bounds.Height) / 2 - 0.75;+ var c = new Point(Bounds.Width / 2, Bounds.Height / 2);+ ctx.DrawEllipse(NotaPalette.BgSunken, new Pen(_fill ?? NotaPalette.BorderStrong, 1.5), c, r, r);+ if (_fill != null) ctx.DrawEllipse(_fill, null, c, r * 0.36, r * 0.36);+ }+}++// ---- dual transistor-ladder response: L (slate) / R (brass) or the series HP→LP curve ----+internal sealed class ConsortFilterCurve : Control+{+ private static readonly Typeface Mono = new("ui-monospace, Menlo, monospace");+ private double _cut = 0.5, _reso, _space, _comp;+ private int _mode = 1;+ private bool _drag;+ public Action<double, double>? Changed;+ public event Action? DragStarted;+ public event Action? DragEnded;+ public ConsortFilterCurve() { Cursor = new Cursor(StandardCursorType.Hand); ClipToBounds = true; }++ public void Set(double cutNorm, double resoNorm, double spacingOct, int mode, bool bassComp)+ { _cut = cutNorm; _reso = resoNorm; _space = spacingOct; _mode = mode; _comp = bassComp ? 1 : 0; InvalidateVisual(); }++ private void Apply(PointerEventArgs e)+ {+ double w = Bounds.Width, h = Bounds.Height; if (w <= 0 || h <= 0) return;+ var p = e.GetPosition(this);+ _cut = Math.Clamp(p.X / w, 0, 1); _reso = Math.Clamp(1 - p.Y / h, 0, 1);+ Changed?.Invoke(_cut, _reso); InvalidateVisual();+ }+ protected override void OnPointerPressed(PointerPressedEventArgs e)+ { base.OnPointerPressed(e); if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return; _drag = true; DragStarted?.Invoke(); Apply(e); e.Pointer.Capture(this); e.Handled = true; }+ protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); if (_drag) Apply(e); }+ protected override void OnPointerReleased(PointerReleasedEventArgs e)+ { base.OnPointerReleased(e); if (_drag) { _drag = false; DragEnded?.Invoke(); e.Pointer.Capture(null); } }++ // |H| of a 4-pole ladder at ω/ωc = wr (resonance k), low-pass or high-pass tap.+ private double Mag(double wr, bool hp)+ {+ double k = 4.3 * _reso * 0.95;+ double r2 = 1 - wr * wr, i2 = 2 * wr;+ double r4 = r2 * r2 - i2 * i2, i4 = 2 * r2 * i2;+ double dr = r4 + k, di = i4;+ double den = Math.Sqrt(dr * dr + di * di);+ double num = hp ? wr * wr * wr * wr : 1;+ return (1 + _comp * k) * num / Math.Max(den, 1e-9);+ }+ private static double Db(double m) => 20 * Math.Log10(Math.Max(m, 1e-6));++ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width, h = Bounds.Height;+ if (w < 2 || h < 2) return;+ ctx.FillRectangle(Brushes.Transparent, new Rect(0, 0, w, h));+ var gp = new Pen(NotaPalette.SurfaceCard, 1);+ foreach (double hz in new[] { 100.0, 1000.0, 10000.0 }) { double gx = Math.Log10(hz / 20) / 3 * w; ctx.DrawLine(gp, new Point(gx, 0), new Point(gx, h)); }+ double y0 = h * 0.42;+ ctx.DrawLine(gp, new Point(0, y0), new Point(w, y0));+ double Y(double db) => Math.Clamp(y0 - db * (h * 0.02), 1, h - 1);+ double cutB = Math.Clamp(_cut + _space / 10.0, -0.5, 1.5); // spacing in decades of the 3-decade axis++ StreamGeometry Curve(Func<double, double> db)+ {+ var g = new StreamGeometry();+ using var c = g.Open();+ c.BeginFigure(new Point(0, Y(db(0))), false);+ for (double x = 1.5; x <= w; x += 1.5) c.LineTo(new Point(x, Y(db(x / w))));+ return g;+ }+ double Wr(double xn, double cn) => Math.Pow(1000, xn - cn);+ var brass = NotaPalette.Accent;+ if (_mode == 0)+ {+ var faint = new SolidColorBrush(Color.FromArgb(0x55, 0x6D, 0x8F, 0xB5));+ ctx.DrawGeometry(null, new Pen(faint, 1), Curve(x => Db(Mag(Wr(x, _cut), true))));+ ctx.DrawGeometry(null, new Pen(brass, 1.5), Curve(x => Db(Mag(Wr(x, _cut), true) * Mag(Wr(x, cutB), false))));+ }+ else+ {+ ctx.DrawGeometry(null, new Pen(ChamberInk.Slate, 1.5), Curve(x => Db(Mag(Wr(x, _cut), _mode == 2))));+ ctx.DrawGeometry(null, new Pen(brass, 1.5), Curve(x => Db(Mag(Wr(x, cutB), false))));+ }+ string Hz(double n) { double hz = 20 * Math.Pow(1000, n); return hz >= 1000 ? $"{hz / 1000:0.00} kHz" : $"{hz:0} Hz"; }+ var lt = new FormattedText((_mode == 0 ? "HP " : "L ") + Hz(_cut), CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 7, _mode == 0 ? NotaPalette.TextSecondary : ChamberInk.Slate);+ var rt = new FormattedText((_mode == 0 ? "LP " : "R ") + Hz(cutB), CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 7, NotaPalette.AccentBright);+ ctx.DrawText(lt, new Point(4, 3));+ ctx.DrawText(rt, new Point(w - rt.Width - 4, 3));+ double hx = Math.Clamp(_cut * w, 4, w - 4), hy = Math.Clamp(Y(Db(Mag(1, _mode == 2 || _mode == 0))), 4, h - 4);+ ctx.DrawEllipse(_mode == 1 ? ChamberInk.Slate : NotaPalette.AccentBright, new Pen(NotaPalette.BgSunken, 2), new Point(hx, hy), 3.5, 3.5);+ }+}++// ---- BBD taps: the L lane on top, R below; bar height = level of each repeat ----+internal sealed class ConsortDelayView : Control+{+ private static readonly Typeface Mono = new("ui-monospace, Menlo, monospace");+ private double _tl = 0.26, _tr = 0.39, _fb = 0.6, _mix = 0.4;+ private bool _ping = true, _digital;+ public ConsortDelayView() { ClipToBounds = true; }+ public void Set(double tl, double tr, double fb, double mix, bool ping, bool digital)+ { _tl = tl; _tr = tr; _fb = fb; _mix = mix; _ping = ping; _digital = digital; InvalidateVisual(); }++ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width, h = Bounds.Height;+ if (w < 2 || h < 2) return;+ ctx.FillRectangle(Brushes.Transparent, new Rect(0, 0, w, h));+ double mid = h / 2;+ ctx.DrawLine(new Pen(NotaPalette.BorderDefault, 1), new Point(0, mid), new Point(w, mid));+ // Taps over a window that shows about four repeats.+ var taps = new List<(double T, double A, bool R)>();+ if (_ping)+ {+ double t = 0, a = 1;+ for (int k = 0; k < 16; k++) { bool r = (k & 1) == 1; t += r ? _tr : _tl; if (k > 0) a *= _fb; taps.Add((t, a, r)); }+ }+ else+ {+ for (int k = 1; k <= 8; k++) { taps.Add((_tl * k, Math.Pow(_fb, k - 1), false)); taps.Add((_tr * k, Math.Pow(_fb, k - 1), true)); }+ }+ double span = Math.Max(_tl, _tr) * 4.2;+ span = ChamberInk.Axis(0, span);+ var bl = ChamberInk.Slate; var br = NotaPalette.Accent;+ foreach (var (t, a, r) in taps)+ {+ if (t > span) continue;+ double x = 6 + (w - 12) * t / span;+ double ht = (mid - 8) * Math.Clamp(ChamberInk.DbHeight(a * Math.Max(0.15, _mix), 48), 0, 1);+ if (ht < 1) continue;+ if (!r) ctx.FillRectangle(bl, new Rect(x - 1.5, mid - 3 - ht, 3, ht));+ else ctx.FillRectangle(br, new Rect(x - 1.5, mid + 3, 3, ht));+ }+ var ll = new FormattedText("L", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 7, bl);+ var rl = new FormattedText("R", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 7, br);+ ctx.DrawText(ll, new Point(4, 2)); ctx.DrawText(rl, new Point(4, h - rl.Height - 1));+ var info = new FormattedText($"fb {_fb * 100:0} % · {(_digital ? "digital" : "compander on")}", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 7, NotaPalette.TextSecondary);+ ctx.DrawText(info, new Point(w - info.Width - 4, 2));+ var ax = new FormattedText(ChamberInk.AxisLabel(span), CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 7, NotaPalette.TextDisabled);+ ctx.DrawText(ax, new Point(w - ax.Width - 4, h - ax.Height - 1));+ }+}++// ---- the 16 step cells: type (note / ratchet / tie / rest), playhead, length. Click / drag paints ----+internal sealed class ConsortStepGrid : Control+{+ private static readonly Typeface Mono = new("ui-monospace, Menlo, monospace");+ private readonly int[] _type = new int[16];+ private int _len = 16, _play = -1, _ratchet = 3;+ private bool _drag; private int _last = -1;+ public event Action<int, bool>? Paint; // (step, erase = right-button / Alt)+ public event Action? PaintStarted;+ public event Action? PaintEnded;+ public ConsortStepGrid() { Cursor = new Cursor(StandardCursorType.Hand); }+ public void Set(ReadOnlySpan<int> types, int len, int play, int ratchet)+ {+ for (int i = 0; i < 16; i++) _type[i] = types[i];+ _len = len; _play = play; _ratchet = ratchet; InvalidateVisual();+ }+ private int Hit(Point p) { double cw = Bounds.Width / 16; int i = (int)(p.X / cw); return i >= 0 && i < 16 ? i : -1; }+ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ base.OnPointerPressed(e);+ var pp = e.GetCurrentPoint(this).Properties;+ if (!pp.IsLeftButtonPressed) return;+ int i = Hit(e.GetPosition(this)); if (i < 0) return;+ _drag = true; _last = i; PaintStarted?.Invoke();+ Paint?.Invoke(i, (e.KeyModifiers & KeyModifiers.Alt) != 0);+ e.Pointer.Capture(this); e.Handled = true;+ }+ protected override void OnPointerMoved(PointerEventArgs e)+ {+ base.OnPointerMoved(e);+ if (!_drag) return;+ int i = Hit(e.GetPosition(this));+ if (i >= 0 && i != _last) { _last = i; Paint?.Invoke(i, (e.KeyModifiers & KeyModifiers.Alt) != 0); }+ }+ protected override void OnPointerReleased(PointerReleasedEventArgs e)+ { base.OnPointerReleased(e); if (_drag) { _drag = false; PaintEnded?.Invoke(); e.Pointer.Capture(null); } }++ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width, h = Bounds.Height;+ if (w < 16 || h < 4) return;+ const double gap = 3;+ double cw = (w - gap * 15) / 16;+ var ac = NotaPalette.AccentColor; var mv = ChamberInk.MauveColor; var tl = Color.Parse("#5B9E9C");+ for (int i = 0; i < 16; i++)+ {+ var r = new Rect(i * (cw + gap) + 0.5, 0.5, cw - 1, h - 1);+ bool inLen = i < _len;+ int t = _type[i];+ (Color c, string lbl) = t switch { 1 => (mv, $"×{_ratchet}"), 2 => (tl, "~"), 3 => (Colors.Transparent, "·"), _ => (ac, (i + 1).ToString(CultureInfo.InvariantCulture)) };+ IBrush fill = t == 3 ? NotaPalette.BgSunken : new SolidColorBrush(Color.FromArgb((byte)(inLen ? 0x40 : 0x14), c.R, c.G, c.B));+ IBrush stroke = t == 3 ? NotaPalette.BorderDefault : new SolidColorBrush(Color.FromArgb((byte)(inLen ? 0xE0 : 0x50), c.R, c.G, c.B));+ ctx.DrawRectangle(fill, new Pen(stroke, i == _play ? 2 : 1), r, 3, 3);+ var ft = new FormattedText(lbl, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, inLen ? (t == 3 ? NotaPalette.TextDisabled : NotaPalette.TextPrimary) : NotaPalette.TextDisabled);+ ctx.DrawText(ft, new Point(r.X + (r.Width - ft.Width) / 2, r.Y + (r.Height - ft.Height) / 2));+ if (i == _play) ctx.DrawRectangle(null, new Pen(NotaPalette.AccentBright, 1), r.Inflate(1.5), 4, 4);+ }+ }+}++// ---- step pitch lane: one bar per step at its pitch (±24 st); drag up/down to set ----+internal sealed class ConsortPitchLane : Control+{+ private static readonly Typeface Sans = new("Inter, system-ui, sans-serif", FontStyle.Normal, FontWeight.Bold);+ private static readonly Typeface Mono = new("ui-monospace, Menlo, monospace");+ private readonly int[] _p = new int[16], _t = new int[16];+ private int _len = 16, _play = -1, _dragStep = -1;+ private bool _arp;+ public event Action<int, int>? PitchChanged; // (step, semitones)+ public event Action<int>? DragStarted;+ public event Action<int>? DragEnded;+ public ConsortPitchLane() { Cursor = new Cursor(StandardCursorType.SizeNorthSouth); ClipToBounds = true; }+ public void Set(ReadOnlySpan<int> pitch, ReadOnlySpan<int> types, int len, int play, bool arp)+ {+ for (int i = 0; i < 16; i++) { _p[i] = pitch[i]; _t[i] = types[i]; }+ _len = len; _play = play; _arp = arp; InvalidateVisual();+ }+ private double Top => 14;+ private int PitchAt(double y) { double hh = Bounds.Height - Top - 4; return Math.Clamp((int)Math.Round((1 - (y - Top) / hh) * 48 - 24), -24, 24); }+ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ base.OnPointerPressed(e);+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;+ var pt = e.GetPosition(this);+ double cw = Bounds.Width / 16; int i = Math.Clamp((int)(pt.X / cw), 0, 15);+ _dragStep = i; DragStarted?.Invoke(i);+ int v = e.ClickCount == 2 ? 0 : PitchAt(pt.Y);+ _p[i] = v; PitchChanged?.Invoke(i, v); InvalidateVisual();+ e.Pointer.Capture(this); e.Handled = true;+ }+ protected override void OnPointerMoved(PointerEventArgs e)+ {+ base.OnPointerMoved(e);+ if (_dragStep < 0) return;+ int v = PitchAt(e.GetPosition(this).Y);+ if (v != _p[_dragStep]) { _p[_dragStep] = v; PitchChanged?.Invoke(_dragStep, v); InvalidateVisual(); }+ }+ protected override void OnPointerReleased(PointerReleasedEventArgs e)+ { base.OnPointerReleased(e); if (_dragStep >= 0) { DragEnded?.Invoke(_dragStep); _dragStep = -1; e.Pointer.Capture(null); } }++ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width, h = Bounds.Height;+ if (w < 16 || h < Top + 6) return;+ ctx.FillRectangle(Brushes.Transparent, new Rect(0, 0, w, h));+ var cap = new FormattedText(_arp ? "PITCH · ARP (STEP TYPES SHAPE THE RHYTHM)" : "PITCH · STEP OFFSETS FROM THE KEY", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Sans, 7, NotaPalette.TextTertiary);+ ctx.DrawText(cap, new Point(6, 3));+ double hh = h - Top - 4, cw = w / 16;+ double Y(int p) => Top + (1 - (p + 24) / 48.0) * hh;+ var grid = new Pen(NotaPalette.SurfaceCard, 1);+ foreach (int p in new[] { -12, 0, 12 }) ctx.DrawLine(grid, new Point(0, Y(p)), new Point(w, Y(p)));+ var ac = NotaPalette.AccentColor; var mv = ChamberInk.MauveColor; var tl = Color.Parse("#5B9E9C");+ for (int i = 0; i < 16; i++)+ {+ if (_t[i] == 3) continue;+ bool on = i < _len;+ byte a = (byte)(_arp ? 0x60 : on ? 0xFF : 0x48);+ var col = _t[i] == 2 ? tl : ac;+ double y = Y(_p[i]);+ var r = new Rect(i * cw + 3, y - 3.5, cw - 6, 7);+ ctx.DrawRectangle(new SolidColorBrush(Color.FromArgb(a, col.R, col.G, col.B)), null, r, 2.5, 2.5);+ if (_t[i] == 1) ctx.DrawRectangle(new SolidColorBrush(Color.FromArgb(a, mv.R, mv.G, mv.B)), null, new Rect(r.X, r.Bottom + 2, r.Width, 4), 2, 2);+ }+ if (_play >= 0 && _play < 16)+ {+ double x = (_play + 0.5) * cw;+ ctx.DrawLine(new Pen(NotaPalette.Accent, 2), new Point(x, Top - 2), new Point(x, h));+ }+ if (_dragStep >= 0)+ {+ var ft = new FormattedText(_p[_dragStep] == 0 ? "0 st" : $"{_p[_dragStep]:+0;-0} st", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, NotaPalette.AccentBright);+ double x = Math.Clamp((_dragStep + 0.5) * cw - ft.Width / 2, 2, w - ft.Width - 2);+ ctx.DrawText(ft, new Point(x, Math.Max(Top, Y(_p[_dragStep]) - 16)));+ }+ }+}++// ---- jack field with cables. Strip mode: grouped rows (label under each jack); List mode:+// titled columns (name beside each jack). Drag jack → jack to patch (out ↔ in), Alt-click a+// jack to pull its cables, right-click for its cable list. ----+internal sealed class ConsortJackField : Control+{+ private static readonly Typeface Mono = new("ui-monospace, Menlo, monospace");+ private static readonly Typeface Sans = new("Inter, system-ui, sans-serif");+ private static readonly Typeface SansBold = new("Inter, system-ui, sans-serif", FontStyle.Normal, FontWeight.Bold);++ public readonly record struct Group(string Title, ConsortJacks.Jack[] Jacks);+ private readonly List<List<Group>> _rows; // strip mode: rows of groups; list mode: columns (one group each)+ private readonly bool _list;+ private readonly Dictionary<(bool, int), Point> _pos = new();+ private IReadOnlyList<ConsortCable> _cables = Array.Empty<ConsortCable>();+ private ConsortJacks.Jack? _from; private Point _drag; private bool _moved;+ private (bool, int)? _hover;++ public event Action<int, int>? Connect; // (source, destination)+ public event Action<ConsortJacks.Jack>? Pull; // Alt-click: remove the jack's cables+ public event Action<ConsortJacks.Jack, Control>? Context; // right-click++ public ConsortJackField(List<List<Group>> rowsOrColumns, bool listMode)+ { _rows = rowsOrColumns; _list = listMode; ClipToBounds = true; Cursor = new Cursor(StandardCursorType.Hand); }++ public void SetCables(IReadOnlyList<ConsortCable> cables) { _cables = cables; InvalidateVisual(); }++ private void Layout()+ {+ _pos.Clear();+ double w = Bounds.Width, h = Bounds.Height;+ if (_list)+ {+ double colW = w / _rows.Count;+ for (int c = 0; c < _rows.Count; c++)+ {+ int k = 0;+ foreach (var g in _rows[c])+ foreach (var j in g.Jacks) { _pos[(j.Out, j.Index)] = new Point(c * colW + 10, 24 + k * 15.5); k++; }+ }+ return;+ }+ int nr = _rows.Count;+ double rowH = h / nr;+ for (int r = 0; r < nr; r++)+ {+ int count = 0; foreach (var g in _rows[r]) count += g.Jacks.Length;+ const double gapG = 10;+ double cw = Math.Min(24, (w - 8 - gapG * (_rows[r].Count - 1)) / Math.Max(1, count));+ double x = 4 + cw / 2;+ double y = r * rowH + rowH * 0.5 + 1;+ foreach (var g in _rows[r])+ {+ foreach (var j in g.Jacks) { _pos[(j.Out, j.Index)] = new Point(x, y); x += cw; }+ x += gapG;+ }+ }+ }++ private ConsortJacks.Jack? HitJack(Point p)+ {+ foreach (var row in _rows)+ foreach (var g in row)+ foreach (var j in g.Jacks)+ if (_pos.TryGetValue((j.Out, j.Index), out var c) && (Math.Abs(p.X - c.X) < 8 || (_list && p.X > c.X && p.X < c.X + 90)) && Math.Abs(p.Y - c.Y) < 7.5)+ return j;+ return null;+ }++ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ base.OnPointerPressed(e);+ var pt = e.GetCurrentPoint(this);+ var j = HitJack(e.GetPosition(this));+ if (j is null) return;+ if (pt.Properties.IsRightButtonPressed) { Context?.Invoke(j.Value, this); e.Handled = true; return; }+ if (!pt.Properties.IsLeftButtonPressed) return;+ if ((e.KeyModifiers & KeyModifiers.Alt) != 0) { Pull?.Invoke(j.Value); e.Handled = true; return; }+ _from = j; _drag = e.GetPosition(this); _moved = false;+ e.Pointer.Capture(this); e.Handled = true; InvalidateVisual();+ }+ protected override void OnPointerMoved(PointerEventArgs e)+ {+ base.OnPointerMoved(e);+ var p = e.GetPosition(this);+ var h = HitJack(p);+ (bool, int)? hv = h is { } hj ? (hj.Out, hj.Index) : null;+ if (hv != _hover) { _hover = hv; InvalidateVisual(); }+ if (_from is null) return;+ _moved = true; _drag = p; InvalidateVisual();+ }+ protected override void OnPointerReleased(PointerReleasedEventArgs e)+ {+ base.OnPointerReleased(e);+ if (_from is not { } f) return;+ var t = HitJack(e.GetPosition(this));+ if (t is { } to && to.Out != f.Out) { if (f.Out) Connect?.Invoke(f.Index, to.Index); else Connect?.Invoke(to.Index, f.Index); }+ else if (!_moved) Context?.Invoke(f, this);+ _from = null; e.Pointer.Capture(null); InvalidateVisual();+ }+ protected override void OnPointerExited(PointerEventArgs e) { base.OnPointerExited(e); if (_hover != null) { _hover = null; InvalidateVisual(); } }++ private static void Cable(DrawingContext ctx, Point a, Point b, IBrush brush, bool list, double thick = 2.4)+ {+ var g = new StreamGeometry();+ using (var c = g.Open())+ {+ c.BeginFigure(a, false);+ if (list) { double dx = (b.X - a.X) * 0.5; c.CubicBezierTo(new Point(a.X + dx, a.Y + 6), new Point(b.X - dx, b.Y + 6), b); }+ else { double sag = 18 + Math.Abs(b.X - a.X) * 0.18; c.CubicBezierTo(new Point(a.X, a.Y + sag), new Point(b.X, b.Y + sag), b); }+ }+ ctx.DrawGeometry(null, new Pen(brush, thick, lineCap: PenLineCap.Round), g);+ }++ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width, h = Bounds.Height;+ if (w < 20 || h < 20) return;+ ctx.FillRectangle(Brushes.Transparent, new Rect(0, 0, w, h));+ Layout();+ // jack colour = the tone of the (first) cable plugged into it+ var lit = new Dictionary<(bool, int), IBrush>();+ foreach (var c in _cables)+ {+ var br = ConsortJacks.ToneBrush(ConsortJacks.Src(c.Src).Tone);+ lit.TryAdd((true, c.Src), br); lit.TryAdd((false, c.Dst), br);+ }+ // captions+ if (_list)+ {+ double colW = w / _rows.Count;+ for (int c = 0; c < _rows.Count; c++)+ {+ var t = new FormattedText(_rows[c][0].Title, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, SansBold, 7.5, NotaPalette.TextTertiary);+ ctx.DrawText(t, new Point(c * colW + 4, 4));+ }+ }+ else+ {+ int nr = _rows.Count; double rowH = h / nr;+ for (int r = 0; r < nr; r++)+ foreach (var g in _rows[r])+ {+ if (g.Jacks.Length == 0 || !_pos.TryGetValue((g.Jacks[0].Out, g.Jacks[0].Index), out var p0)) continue;+ var t = new FormattedText(g.Title, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, SansBold, 7, NotaPalette.TextTertiary);+ ctx.DrawText(t, new Point(p0.X - 5, r * rowH + rowH * 0.5 - 17));+ }+ }+ // jacks+ foreach (var row in _rows)+ foreach (var g in row)+ foreach (var j in g.Jacks)+ {+ if (!_pos.TryGetValue((j.Out, j.Index), out var p)) continue;+ bool hov = _hover == (j.Out, j.Index) || (_from is { } f && f.Out == j.Out && f.Index == j.Index);+ lit.TryGetValue((j.Out, j.Index), out var col);+ if (j.Out) ctx.DrawEllipse(null, new Pen(NotaPalette.SurfaceRaised, 2), p, 7.5, 7.5); // output collar+ ctx.DrawEllipse(NotaPalette.BgSunken, new Pen(col ?? (hov ? NotaPalette.TextSecondary : NotaPalette.BorderStrong), 1.6), p, 5.5, 5.5);+ if (col != null) ctx.DrawEllipse(col, null, p, 2, 2);+ if (_list)+ {+ var t = new FormattedText(j.Name, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Sans, 8.5, col != null || hov ? NotaPalette.TextPrimary : NotaPalette.TextTertiary);+ ctx.DrawText(t, new Point(p.X + 10, p.Y - t.Height / 2));+ }+ else+ {+ var t = new FormattedText(j.Short, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 6.5, col != null ? NotaPalette.TextSecondary : NotaPalette.TextDisabled);+ ctx.DrawText(t, new Point(p.X - t.Width / 2, p.Y + 7));+ }+ }+ // cables over the jacks+ foreach (var c in _cables)+ {+ if (!_pos.TryGetValue((true, c.Src), out var a) || !_pos.TryGetValue((false, c.Dst), out var b)) continue;+ var col = ConsortJacks.ToneColor(ConsortJacks.Src(c.Src).Tone);+ Cable(ctx, a, b, new SolidColorBrush(Color.FromArgb(0xDC, col.R, col.G, col.B)), _list);+ ctx.DrawEllipse(new SolidColorBrush(col), null, a, 2, 2); ctx.DrawEllipse(new SolidColorBrush(col), null, b, 2, 2);+ }+ if (_from is { } fr && _moved && _pos.TryGetValue((fr.Out, fr.Index), out var fp))+ {+ var col = fr.Out ? ConsortJacks.ToneColor(fr.Tone) : NotaPalette.AccentBrightColor;+ Cable(ctx, fp, _drag, new SolidColorBrush(Color.FromArgb(0x90, col.R, col.G, col.B)), _list, 2);+ }+ // hover tooltip-ish caption in strip mode: the full jack name+ if (!_list && _hover is { } hk)+ {+ var j = hk.Item1 ? ConsortJacks.Src(hk.Item2) : ConsortJacks.Dst(hk.Item2);+ if (_pos.TryGetValue(hk, out var p))+ {+ var t = new FormattedText($"{j.Name} · {(j.Out ? "out" : "in")}", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Sans, 8, NotaPalette.TextPrimary);+ double x = Math.Clamp(p.X - t.Width / 2, 1, w - t.Width - 1), y = p.Y - 21;+ if (y < 1) y = p.Y + 15;+ ctx.DrawRectangle(NotaPalette.SurfaceRaised, new Pen(NotaPalette.BorderStrong, 1), new Rect(x - 3, y - 1, t.Width + 6, t.Height + 2), 3, 3);+ ctx.DrawText(t, new Point(x, y));+ }+ }+ }+}++// ---- source × destination matrix: rows = sources, columns = destinations, cell = depth ----+internal sealed class ConsortPatchMatrix : Control+{+ private static readonly Typeface Mono = new("ui-monospace, Menlo, monospace");+ private static readonly Typeface Sans = new("Inter, system-ui, sans-serif");+ private static readonly Typeface SansBold = new("Inter, system-ui, sans-serif", FontStyle.Normal, FontWeight.Bold);+ private int[] _rows = Array.Empty<int>(), _cols = Array.Empty<int>();+ private IReadOnlyList<ConsortCable> _cables = Array.Empty<ConsortCable>();+ private const double HeadH = 16, RowHdrW = 78;+ private (int r, int c)? _drag; private double _dragY, _dragV;++ public event Action<int, int, float>? DepthChanged; // (src, dst, depth) — creates the cable when missing+ public event Action<int, int>? Removed; // (src, dst)+ public event Action<int, int>? GestureBegin;+ public event Action<int, int>? GestureEnd;+ public event Action<bool, int, Rect>? HeaderClicked; // (isRow, index, rect)++ public ConsortPatchMatrix() { ClipToBounds = true; Cursor = new Cursor(StandardCursorType.Hand); }+ public void Set(int[] rows, int[] cols, IReadOnlyList<ConsortCable> cables) { _rows = rows; _cols = cols; _cables = cables; InvalidateVisual(); }++ private double RowH => _rows.Length == 0 ? 0 : (Bounds.Height - HeadH) / _rows.Length;+ private double ColW => _cols.Length == 0 ? 0 : (Bounds.Width - RowHdrW) / _cols.Length;+ private ConsortCable? Find(int s, int d) { foreach (var c in _cables) if (c.Src == s && c.Dst == d) return c; return null; }++ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ base.OnPointerPressed(e);+ var pt = e.GetCurrentPoint(this);+ if (!pt.Properties.IsLeftButtonPressed) return;+ var p = e.GetPosition(this);+ if (p.Y < HeadH && p.X >= RowHdrW) { int c = (int)((p.X - RowHdrW) / ColW); if (c >= 0 && c < _cols.Length) HeaderClicked?.Invoke(false, c, new Rect(RowHdrW + c * ColW, 0, ColW, HeadH)); e.Handled = true; return; }+ if (p.X < RowHdrW && p.Y >= HeadH) { int r = (int)((p.Y - HeadH) / RowH); if (r >= 0 && r < _rows.Length) HeaderClicked?.Invoke(true, r, new Rect(0, HeadH + r * RowH, RowHdrW, RowH)); e.Handled = true; return; }+ if (p.X < RowHdrW || p.Y < HeadH) return;+ int ri = (int)((p.Y - HeadH) / RowH), ci = (int)((p.X - RowHdrW) / ColW);+ if (ri < 0 || ri >= _rows.Length || ci < 0 || ci >= _cols.Length) return;+ int s = _rows[ri], d = _cols[ci];+ var cur = Find(s, d);+ if ((e.KeyModifiers & KeyModifiers.Alt) != 0 || (e.ClickCount == 2 && cur != null)) { Removed?.Invoke(s, d); e.Handled = true; return; }+ _drag = (ri, ci); _dragY = p.Y; _dragV = cur?.Depth ?? 0;+ GestureBegin?.Invoke(s, d);+ if (cur == null) { _dragV = 0.5; DepthChanged?.Invoke(s, d, 0.5f); }+ e.Pointer.Capture(this); e.Handled = true;+ }+ protected override void OnPointerMoved(PointerEventArgs e)+ {+ base.OnPointerMoved(e);+ if (_drag is not { } dg) return;+ double y = e.GetPosition(this).Y;+ bool fine = (e.KeyModifiers & (KeyModifiers.Control | KeyModifiers.Meta | KeyModifiers.Shift)) != 0;+ _dragV = Math.Clamp(_dragV + (_dragY - y) / (fine ? 1000.0 : 100.0), -1, 1); _dragY = y;+ DepthChanged?.Invoke(_rows[dg.r], _cols[dg.c], (float)Math.Round(_dragV * 100) / 100f);+ }+ protected override void OnPointerReleased(PointerReleasedEventArgs e)+ {+ base.OnPointerReleased(e);+ if (_drag is not { } dg) return;+ GestureEnd?.Invoke(_rows[dg.r], _cols[dg.c]);+ _drag = null; e.Pointer.Capture(null);+ }++ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width, h = Bounds.Height;+ if (w < 40 || h < 30 || _rows.Length == 0 || _cols.Length == 0) return;+ ctx.FillRectangle(Brushes.Transparent, new Rect(0, 0, w, h));+ double rh = RowH, cw = ColW;+ var corner = new FormattedText("SRC → DST", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, SansBold, 7, NotaPalette.TextDisabled);+ ctx.DrawText(corner, new Point(4, (HeadH - corner.Height) / 2));+ for (int c = 0; c < _cols.Length; c++)+ {+ var d = ConsortJacks.Dst(_cols[c]);+ var t = new FormattedText(d.Name, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, SansBold, 7.5, NotaPalette.TextSecondary) { MaxTextWidth = cw - 4, MaxLineCount = 1, Trimming = TextTrimming.CharacterEllipsis };+ ctx.DrawText(t, new Point(RowHdrW + c * cw + (cw - t.Width) / 2, (HeadH - t.Height) / 2));+ }+ var line = new Pen(NotaPalette.BorderDefault, 1);+ for (int r = 0; r < _rows.Length; r++)+ {+ double y = HeadH + r * rh;+ ctx.DrawLine(line, new Point(0, y), new Point(w, y));+ var s = ConsortJacks.Src(_rows[r]);+ var t = new FormattedText(s.Name, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Sans, 8.5, NotaPalette.TextPrimary) { MaxTextWidth = RowHdrW - 6, MaxLineCount = 1, Trimming = TextTrimming.CharacterEllipsis };+ ctx.DrawText(t, new Point(4, y + (rh - t.Height) / 2));+ var tc = ConsortJacks.ToneColor(s.Tone);+ for (int c = 0; c < _cols.Length; c++)+ {+ var cell = new Rect(RowHdrW + c * cw + 2, y + 3, cw - 4, rh - 6);+ var cab = Find(_rows[r], _cols[c]);+ if (cab is { } cb)+ {+ ctx.DrawRectangle(new SolidColorBrush(Color.FromArgb(0x30, tc.R, tc.G, tc.B)), new Pen(new SolidColorBrush(tc), 1.2), cell, 3, 3);+ // depth bar from the centre+ double mid = cell.X + cell.Width / 2, bw = cell.Width / 2 * Math.Abs(cb.Depth);+ ctx.FillRectangle(new SolidColorBrush(Color.FromArgb(0x38, tc.R, tc.G, tc.B)), new Rect(cb.Depth >= 0 ? mid : mid - bw, cell.Bottom - 3, bw, 2));+ var v = new FormattedText($"{cb.Depth * 100:+0;-0;0}", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, NotaPalette.TextPrimary);+ ctx.DrawText(v, new Point(cell.X + (cell.Width - v.Width) / 2, cell.Y + (cell.Height - v.Height) / 2));+ }+ else+ {+ ctx.DrawRectangle(NotaPalette.BgSunken, new Pen(NotaPalette.BorderDefault, 1), cell, 3, 3);+ var v = new FormattedText("·", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, NotaPalette.TextDisabled);+ ctx.DrawText(v, new Point(cell.X + (cell.Width - v.Width) / 2, cell.Y + (cell.Height - v.Height) / 2));+ }+ }+ }+ }+}diff --git a/src/managed/Nota.App/DeviceCards/InstrumentCardFactory.cs b/src/managed/Nota.App/DeviceCards/InstrumentCardFactory.csindex e959771e..5c6c72d9 100644--- a/src/managed/Nota.App/DeviceCards/InstrumentCardFactory.cs+++ b/src/managed/Nota.App/DeviceCards/InstrumentCardFactory.cs@@ -27,6 +27,7 @@ internal sealed class InstrumentCardFactory[12] = new RhythmInstrumentCard(),[13] = new MonolithInstrumentCard(),[14] = new PentadInstrumentCard(),+ [15] = new ConsortInstrumentCard(),};/// <summary>Resolve the editor for a built-in instrument kind. The Sampler (1) alwaysdiff --git a/src/managed/Nota.App/DeviceCards/Instruments/ConsortInstrumentCard.cs b/src/managed/Nota.App/DeviceCards/Instruments/ConsortInstrumentCard.csnew file mode 100644index 00000000..4dda7dd1--- /dev/null+++ b/src/managed/Nota.App/DeviceCards/Instruments/ConsortInstrumentCard.cs@@ -0,0 +1,1190 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Detail · Devices — built-in Nota Consort editor (instrument kind 15), a build of the+// "Nota Consort" mockup (700 × 260) on the Monolith / Pentad frame: an always-visible+// WHEELS column, a centre tabbed panel (Osc · Mix / Filters · Env / LFO · Delay / Seq /+// Patch), a right tabbed panel (Voices / Output), the collapsed PATCH BAY row (active+// cables + the entry to the full-card patch overlay) and a status strip. The patch bay has+// three views of the same twelve cables: the source × destination matrix and the jack strip+// inside the Patch tab, and the overlay with all 42 points. Every control is a plugin-param+// (cables included), so automation / MIDI learn / presets / persistence come for free.+// BodyOnly — the shared shell draws the header (name / preset / A-B / meter).++using System;+using System.Collections.Generic;+using System.Linq;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Controls.Primitives;+using Avalonia.Input;+using Avalonia.Layout;+using Avalonia.Media;+using Avalonia.Threading;+using Nota.Application;+using static Nota.App.DeviceCardKit;++namespace Nota.App;++internal sealed class ConsortInstrumentCard : IInstrumentCard+{+ private static readonly IBrush RailBg = new SolidColorBrush(Color.Parse("#1B1916"));+ private static readonly IBrush Panel = NotaPalette.BgApp;+ private static readonly IBrush Border2 = NotaPalette.BorderDefault;+ private static readonly IBrush BorderIn = new SolidColorBrush(Color.Parse("#221F1A"));+ private static readonly IBrush Inset = NotaPalette.BgSunken;+ private static readonly IBrush TabBg = NotaPalette.SurfaceCard;+ private static readonly IBrush Amber = NotaPalette.Accent;+ private static readonly IBrush AmberLit = NotaPalette.AccentBright;+ private static readonly IBrush TealC = NotaPalette.Teal;+ private static readonly IBrush TxtC = NotaPalette.TextPrimary;+ private static readonly IBrush Txt2 = NotaPalette.TextSecondary;+ private static readonly IBrush MutedC = NotaPalette.TextTertiary;+ private static readonly IBrush DimC = NotaPalette.TextDisabled;+ private static readonly IBrush Handle = NotaPalette.TextSecondary;+ private static readonly IBrush OffPill = NotaPalette.SurfaceRaised;+ private static readonly IBrush AmberSubtle = NotaPalette.AccentSubtle;++ private static readonly string[] Feet = { "32′", "16′", "8′", "4′", "2′" };+ private static readonly string[] SyncNames = { "8 bar", "4 bar", "2 bar", "1 bar", "1/2", "1/4.", "1/4", "1/8.", "1/4T", "1/8", "1/8T", "1/16", "1/16T", "1/32" };+ private static readonly string[] SeqRates = { "1/4", "1/8", "1/8T", "1/16", "1/16T", "1/32" };+ private static readonly string[] LfoNames = { "sine", "ramp up", "ramp down", "square", "S&H", "smooth random" };+ // Compact names for the patch-bay row chips (index == jack index).+ private static readonly string[] SrcChip = { "", "LFO", "Env1", "Env2", "Osc1", "Osc2", "Osc3", "Osc4", "Noise", "Filt", "Seq", "SeqGt", "Clk", "Kbd", "KbdGt", "Vel", "AT", "Wheel", "Att1", "Att2", "Sum" };+ private static readonly string[] DstChip = { "", "Rate", "Gate1", "Gate2", "Pitch", "Osc1", "Osc2", "Osc3", "Osc4", "PWM", "Filt", "Filt2", "Res", "FiltIn", "VCA", "VCAin", "Dly", "DlyFb", "DlyMix", "Ext", "Att1", "Att2", "Sum" };+ private const int Cables = 12;++ // View state that survives a rebuild (preset change, undo): per track.+ private sealed class ViewState+ {+ public int Centre, Right, PatchView, LastNonPatch, Brush;+ public bool Overlay;+ public readonly List<int> RowPrefs = new() { 1, 2, 10, 6, 15 }; // LFO out, Env 1, Seq pitch, Osc 3, Velocity+ public readonly List<int> ColPrefs = new() { 4, 9, 16, 10, 14 }; // Osc pitch, PWM, Delay time, Filt 1, VCA CV+ }+ private static readonly Dictionary<int, ViewState> Views = new();++ public bool BodyOnly => true;+ public string Subtitle => "PARAPHONIC";++ public string? VoiceLabel(IAudioEngine engine, int trackId, int active)+ {+ // Fixed layout (Consort.h): voicemode = 7, truepoly = 8; verified, with a scan fallback.+ float G(string id, int at)+ {+ if (engine.PluginParamId(trackId, -1, at) == id) return engine.PluginParamGet(trackId, -1, at);+ int n = engine.PluginParamCount(trackId, -1);+ for (int i = 0; i < n; i++) if (engine.PluginParamId(trackId, -1, i) == id) return engine.PluginParamGet(trackId, -1, i);+ return 0;+ }+ int a = Math.Max(0, active);+ if (G("truepoly", 8) > 0.5f) return $"POLY {a}/16";+ return Math.Clamp((int)Math.Round(G("voicemode", 7) * 2), 0, 2) switch { 0 => "MONO", 1 => $"DUO {a}/2", _ => $"PARA {a}/4" };+ }++ public Control Build(DeviceCardContext ctx)+ {+ var engine = ctx.Engine;+ int track = ctx.TrackId;+ if (!Views.TryGetValue(track, out var vs)) Views[track] = vs = new ViewState();+ int pc = engine.PluginParamCount(track, -1);+ var idx = new Dictionary<string, int>();+ for (int i = 0; i < pc; i++) idx[engine.PluginParamId(track, -1, i)] = i;+ float G(string id) => idx.TryGetValue(id, out var i) ? engine.PluginParamGet(track, -1, i) : 0f;+ int I(string id) => idx.TryGetValue(id, out var i) ? i : -1;+ bool On(string id) => G(id) > 0.5f;+ int Sel(string id, int n) => Math.Clamp((int)Math.Round(G(id) * (n - 1)), 0, n - 1);+ void Begin(string id) => engine.BeginAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id);+ void End(string id) => engine.EndAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id);+ List<ConsortCable>? cableCache = null; // one read of the 36 cable params per tick / edit+ void Raw(string id, float v) { if (I(id) is var i and >= 0) { engine.PluginParamSet(track, -1, i, Math.Clamp(v, 0f, 1f)); cableCache = null; } }+ // A discrete edit (click) is one automation gesture, so Touch/Latch/Write record it.+ void SetP(string id, float v) { if (I(id) < 0) return; Begin(id); Raw(id, v); End(id); }++ var common = new List<Action>();+ var tabReadouts = new[] { new List<Action>(), new List<Action>(), new List<Action>(), new List<Action>(), new List<Action>() };+ var rightReadouts = new[] { new List<Action>(), new List<Action>() };+ var overlayReadouts = new List<Action>();+ List<Action> cur = common; // helpers register their refreshers here while a body is built+ var scope = new float[32];+ int scN = 0;+ Action refreshAll = () => { };+ Action patchShow = () => { };+ void Refresh() => refreshAll();++ // ---- small builders --------------------------------------------------------+ static TextBlock Lbl(string t, double fs, IBrush c, FontWeight w = FontWeight.Bold)+ => new() { Text = t, FontSize = fs, FontWeight = w, Foreground = c, VerticalAlignment = VerticalAlignment.Center };+ static TextBlock Caps(string t) => new() { Text = t, FontSize = 7, FontWeight = FontWeight.Bold, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center, LetterSpacing = 0.8 };+ static TextBlock MonoText(string t, double fs, IBrush c)+ { var tb = new TextBlock { Text = t, FontSize = fs, Foreground = c, VerticalAlignment = VerticalAlignment.Center }; tb.BindResource(TextBlock.FontFamilyProperty, "Font.Mono"); return tb; }+ static StackPanel Row(double sp, params Control[] cs)+ { var s = new StackPanel { Orientation = Orientation.Horizontal, Spacing = sp, VerticalAlignment = VerticalAlignment.Center }; foreach (var c in cs) s.Children.Add(c); return s; }+ static Control Docked(Control c, Dock d) { DockPanel.SetDock(c, d); return c; }+ static Control Col(Control c, int col) { Grid.SetColumn(c, col); return c; }+ static Control RowAt(Control c, int r) { Grid.SetRow(c, r); return c; }+ static Border Divider(Control child, double top = 5) => new() { BorderBrush = BorderIn, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, top, 0, 0), Child = child };+ static Control Right(Control c) { c.HorizontalAlignment = HorizontalAlignment.Right; return c; }+ static Control Center(Control c) { c.HorizontalAlignment = HorizontalAlignment.Center; return c; }++ Control K(string id, string name, Func<float, string> fmt, bool mod = false, double sz = 28, double cw = 44)+ => InstrumentControls.InstKnob(ctx, idx, id, name, Refresh, fmt, sz, cw, mod ? TealC : null);++ // A compact horizontal knob: [knob] value — for the oscillator table.+ Control MiniKnob(string id, Func<float, string> fmt, double size, double valW, IBrush valColor)+ {+ if (I(id) is not (var i and >= 0)) return new Panel();+ var value = MonoText(fmt(G(id)), 8, valColor); value.Width = valW;+ var knob = new Knob(G(id), 1.0) { Accent = true, Default = engine.InstrumentParamDefault(track, i), Width = size, Height = size };+ knob.ValueChanged += v => { engine.PluginParamSet(track, -1, i, (float)v); value.Text = fmt((float)v); Refresh(); };+ knob.GestureBegin += () => Begin(id);+ knob.GestureEnd += () => End(id);+ ctx.AddInstFader(i, knob, value, fmt);+ MidiLearn.Bind(knob, MidiTarget.PluginParam(track, -1, i), id);+ return Row(4, knob, value);+ }++ // On/off pill toggle backed by a param (> 0.5 = on).+ Control Toggle(string id, string label, Func<bool>? dim = null)+ {+ var pill = new Border { Width = 18, Height = 10, CornerRadius = new CornerRadius(5), VerticalAlignment = VerticalAlignment.Center };+ var dot = new Border { Width = 7, Height = 7, CornerRadius = new CornerRadius(4) };+ var host = new Canvas { Width = 18, Height = 10 }; Canvas.SetTop(dot, 1.5); host.Children.Add(dot); pill.Child = host;+ var txt = new TextBlock { Text = label, FontSize = 8, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center };+ void Hi()+ {+ bool on = On(id), d = dim?.Invoke() ?? false;+ pill.Background = on ? (d ? NotaPalette.BorderStrong : Amber) : OffPill; dot.Background = on ? Panel : MutedC; Canvas.SetLeft(dot, on ? 9.5 : 1.5);+ txt.Foreground = d ? DimC : on ? TxtC : Txt2;+ }+ var wrap = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Children = { pill } };+ if (label.Length > 0) wrap.Children.Add(txt);+ wrap.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(wrap).Properties.IsLeftButtonPressed) return; SetP(id, On(id) ? 0f : 1f); Refresh(); e.Handled = true; };+ cur.Add(Hi); Hi();+ if (I(id) is var pi and >= 0) MidiLearn.Bind(wrap, MidiTarget.PluginParam(track, -1, pi), label.Length > 0 ? label : id);+ return wrap;+ }++ // Segmented chips. values[i] is written on click; the lit chip is the nearest value.+ Control Chips(string id, string[] names, float[]? values = null, double fs = 7, Func<bool>? dim = null)+ {+ int n = names.Length;+ values ??= BuildValues(n);+ var arr = new Border[n];+ void Hi()+ {+ float c0 = G(id); int best = 0;+ for (int i = 1; i < n; i++) if (Math.Abs(values[i] - c0) < Math.Abs(values[best] - c0)) best = i;+ bool exact = Math.Abs(values[best] - c0) < 0.02f, d = dim?.Invoke() ?? false;+ for (int i = 0; i < n; i++)+ {+ bool on = i == best && exact;+ arr[i].Background = on ? (d ? NotaPalette.BorderStrong : Amber) : Brushes.Transparent;+ var tb = (TextBlock)arr[i].Child!; tb.Foreground = on ? Panel : d ? DimC : MutedC; tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;+ }+ }+ var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 1 };+ for (int i = 0; i < n; i++)+ {+ int iv = i;+ var c = new Border { CornerRadius = new CornerRadius(2), Padding = new Thickness(4, 0), Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = names[i], FontSize = fs, Foreground = MutedC } };+ c.PointerPressed += (_, e) => { SetP(id, values[iv]); Refresh(); e.Handled = true; };+ arr[i] = c; row.Children.Add(c);+ }+ cur.Add(Hi); Hi();+ var seg = new Border { Background = Inset, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(3), Padding = new Thickness(1), VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Child = row };+ if (I(id) is var pi and >= 0) MidiLearn.Bind(seg, MidiTarget.PluginParam(track, -1, pi), id);+ return seg;+ }+ static float[] BuildValues(int n) { var v = new float[n]; for (int i = 0; i < n; i++) v[i] = n > 1 ? i / (float)(n - 1) : 0f; return v; }++ // A segmented control over view state (not a param).+ Control ViewSeg(string[] names, Func<int> get, Action<int> set)+ {+ var arr = new Border[names.Length];+ void Hi() { for (int i = 0; i < arr.Length; i++) { bool on = i == get(); arr[i].Background = on ? Amber : Brushes.Transparent; var tb = (TextBlock)arr[i].Child!; tb.Foreground = on ? Panel : MutedC; tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal; } }+ var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 1 };+ for (int i = 0; i < names.Length; i++)+ {+ int iv = i;+ var c = new Border { CornerRadius = new CornerRadius(2), Padding = new Thickness(5, 0), Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = names[i], FontSize = 7.5 } };+ c.PointerPressed += (_, e) => { set(iv); Hi(); e.Handled = true; };+ arr[i] = c; row.Children.Add(c);+ }+ Hi();+ return new Border { Background = Inset, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(3), Padding = new Thickness(1), VerticalAlignment = VerticalAlignment.Center, Child = row };+ }++ // Horizontal fill slider bound to a param; `dim` greys it out.+ Control HSlider(string id, Func<double, string> fmt, double valW = 24, Func<bool>? dim = null, bool bipolar = false)+ {+ int pi = I(id);+ var fill = new Border { Height = 3, Background = Amber, CornerRadius = new CornerRadius(2), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center };+ var handle = new Border { Width = 6, Height = 7, Background = Handle, CornerRadius = new CornerRadius(2) };+ var lay = new Canvas { Height = 9 };+ lay.Children.Add(handle); Canvas.SetTop(handle, 1);+ var canvas = new Panel { Height = 11, MinWidth = 24, Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Children = {+ new Border { Height = 3, Background = Inset, CornerRadius = new CornerRadius(2), VerticalAlignment = VerticalAlignment.Center }, fill, lay } };+ var val = MonoText("", 8, TxtC); val.MinWidth = valW; val.TextAlignment = TextAlignment.Right;+ bool drag = false;+ void Vis(double v)+ {+ double w = canvas.Bounds.Width; if (w <= 0) w = 80;+ double a = bipolar ? Math.Min(v, 0.5) : 0, b = bipolar ? Math.Max(v, 0.5) : v;+ fill.Margin = new Thickness(a * w, 0, 0, 0); fill.Width = Math.Max(0, (b - a) * w);+ Canvas.SetLeft(handle, v * w - 3); val.Text = fmt(v);+ bool d = dim?.Invoke() ?? false;+ fill.Background = d ? NotaPalette.BorderStrong : Amber; handle.Background = d ? MutedC : Handle; val.Foreground = d ? Txt2 : TxtC;+ }+ void From(PointerEventArgs e) { double w = canvas.Bounds.Width; double v = w > 0 ? Math.Clamp(e.GetPosition(canvas).X / w, 0, 1) : 0; if (pi >= 0) engine.PluginParamSet(track, -1, pi, (float)v); Vis(v); Refresh(); }+ canvas.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(canvas).Properties.IsLeftButtonPressed) return;+ if (e.ClickCount == 2 && pi >= 0) { SetP(id, engine.InstrumentParamDefault(track, pi)); Refresh(); e.Handled = true; return; }+ drag = true; if (pi >= 0) Begin(id); e.Pointer.Capture(canvas); From(e); e.Handled = true;+ };+ canvas.PointerMoved += (_, e) => { if (drag) From(e); };+ canvas.PointerReleased += (_, e) => { if (drag) { drag = false; if (pi >= 0) End(id); e.Pointer.Capture(null); } };+ canvas.SizeChanged += (_, _) => Vis(G(id));+ cur.Add(() => { if (!drag) Vis(G(id)); });+ var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 5, VerticalAlignment = VerticalAlignment.Center };+ grid.Children.Add(canvas); grid.Children.Add(Col(val, 1));+ if (pi >= 0) MidiLearn.Bind(grid, MidiTarget.PluginParam(track, -1, pi), id);+ return grid;+ }+ Control SliderRow(string label, string id, Func<double, string> fmt, double labW = 40, double valW = 26, Func<bool>? dim = null, bool bipolar = false)+ {+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions($"{labW},*"), VerticalAlignment = VerticalAlignment.Center };+ g.Children.Add(Caps(label)); g.Children.Add(Col(HSlider(id, fmt, valW, dim, bipolar), 1));+ return g;+ }++ // Vertical wheel bound to a param (pitch springs back to centre).+ Control VWheel(string id, string name, IBrush lit, bool spring)+ {+ int pi = I(id);+ var grad = new LinearGradientBrush { StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative), EndPoint = new RelativePoint(0, 1, RelativeUnit.Relative),+ GradientStops = { new GradientStop(Color.Parse("#26231E"), 0), new GradientStop(Color.Parse("#100F0D"), 0.5), new GradientStop(Color.Parse("#26231E"), 1) } };+ var bar = new Border { Width = 16, Background = grad, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(8), VerticalAlignment = VerticalAlignment.Stretch };+ var mark = new Border { Height = 2, Width = 12, Background = lit, CornerRadius = new CornerRadius(1) };+ var lay = new Canvas { Width = 16 };+ lay.Children.Add(mark); Canvas.SetLeft(mark, 2);+ var host = new Panel { Width = 16, VerticalAlignment = VerticalAlignment.Stretch, Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.SizeNorthSouth), Children = { bar, lay } };+ bool drag = false; DispatcherTimer? springT = null;+ void Vis(double v) { double h = host.Bounds.Height; if (h <= 0) h = 90; Canvas.SetTop(mark, (1 - v) * (h - 2)); }+ void From(PointerEventArgs e) { double h = host.Bounds.Height; double v = h > 0 ? Math.Clamp(1 - e.GetPosition(host).Y / h, 0, 1) : 0.5; if (pi >= 0) engine.PluginParamSet(track, -1, pi, (float)v); Vis(v); Refresh(); }+ void Spring()+ {+ springT?.Stop();+ springT = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(16) };+ springT.Tick += (_, _) =>+ {+ double v = G(id); v += (0.5 - v) * 0.32;+ if (Math.Abs(v - 0.5) < 0.002) { v = 0.5; springT!.Stop(); }+ if (pi >= 0) engine.PluginParamSet(track, -1, pi, (float)v); Vis(v); Refresh();+ };+ springT.Start();+ }+ host.PointerPressed += (_, e) => { springT?.Stop(); drag = true; if (pi >= 0) Begin(id); e.Pointer.Capture(host); From(e); };+ host.PointerMoved += (_, e) => { if (drag) From(e); };+ host.PointerReleased += (_, e) => { if (drag) { drag = false; if (pi >= 0) End(id); e.Pointer.Capture(null); if (spring) Spring(); } };+ host.SizeChanged += (_, _) => Vis(G(id));+ var nm = new TextBlock { Text = name, FontSize = 7, FontWeight = FontWeight.Bold, Foreground = MutedC, HorizontalAlignment = HorizontalAlignment.Center };+ common.Add(() => { if (!drag) Vis(G(id)); bool live = Math.Abs(G(id) - (spring ? 0.5f : 0f)) > 0.01f; nm.Foreground = live ? AmberLit : MutedC; });+ var col = new DockPanel { HorizontalAlignment = HorizontalAlignment.Center };+ DockPanel.SetDock(nm, Avalonia.Controls.Dock.Bottom);+ col.Children.Add(nm); col.Children.Add(host);+ if (pi >= 0) MidiLearn.Bind(col, MidiTarget.PluginParam(track, -1, pi), name);+ return col;+ }++ // ---- formatters -------------------------------------------------------------+ static double Exp(double lo, double hi, double v) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0, 1));+ static string Time(double s) => s >= 1 ? $"{s:0.0} s" : s >= 0.0995 ? $"{s * 1000:0} ms" : $"{s * 1000:0.#} ms";+ static string ShortTime(double s) => s >= 1 ? $"{s:0.0}s" : $"{s * 1000:0}ms";+ static string Pct(double v) => $"{v * 100:0} %";+ static string Tenths(double v) => $"{v * 10:0.0}";+ static string HzFmt(double hz) => hz >= 1000 ? $"{hz / 1000:0.00} kHz" : $"{hz:0} Hz";+ static string Signed(double v, string f) => Math.Abs(v) < 0.005 ? (0.0).ToString(f) : v.ToString("+" + f + ";-" + f);+ string Foot(float v) => Feet[Math.Clamp((int)Math.Round(v * 4), 0, 4)];+ string Freq(float v) => Signed((v - 0.5) * 14, "0.00");+ string Cut(float v) => HzFmt(20 * Math.Pow(1000, v));+ string Space(float v) => Signed((v - 0.5) * 6, "0.0") + " oct";+ string EnvAmt(float v) => Signed((v - 0.5) * 20, "0.0");+ string Atk(float v) => ShortTime(Exp(0.001, 10, v));+ string Dec(float v) => ShortTime(Exp(0.003, 15, v));+ string GlideF(double v) => v < 0.002 ? "off" : Time(Exp(0.005, 5, v));+ string LfoRate(float v) => On("lfosync") ? SyncNames[Math.Clamp((int)Math.Round(v * 13), 0, 13)] : $"{Exp(0.05, 30, v):0.0#} Hz";+ static double LfoCentsOf(double v) { double b = (v - 0.5) * 2; return b * Math.Abs(b) * 1200; }+ string LfoCents(float v) { double c = LfoCentsOf(v); return Math.Abs(c) < 0.5 ? "0 c" : $"{c:+0;-0} c"; }+ static double DlySec(double v) => Exp(0.02, 1.5, v);+ string DlyMs(float v) => $"{DlySec(v) * 1000:0} ms";+ string DlySpc(float v) => $"{(v - 0.5) * 1000:+0;-0;0} ms";+ string VolDb(float v) { double g = 2 * v * v; return g <= 1e-4 ? "−∞" : $"{20 * Math.Log10(g):0.0} dB"; }+ string Tune(double v) => Signed((v - 0.5) * 4, "0.0") + " st";+ int BendSt() => 1 + Math.Clamp((int)Math.Round(G("bendrange") * 11), 0, 11);+ string Depth(double v) => $"{(v - 0.5) * 200:+0;-0;0}";++ // ======================================================================+ // Patch-bay model: 12 cable slots of (source, destination, depth) params+ // ======================================================================+ string SrcId(int k) => $"c{k + 1}src";+ string DstId(int k) => $"c{k + 1}dst";+ string AmtId(int k) => $"c{k + 1}amt";+ List<ConsortCable> CableList() => cableCache ??= ReadCables();+ List<ConsortCable> ReadCables()+ {+ var l = new List<ConsortCable>();+ for (int k = 0; k < Cables; k++)+ {+ int s = ConsortJacks.FromNorm(G(SrcId(k))), d = ConsortJacks.FromNorm(G(DstId(k)));+ if (s <= 0 || d <= 0 || s >= ConsortJacks.Sources.Length || d >= ConsortJacks.Dests.Length) continue;+ l.Add(new ConsortCable(k, s, d, (G(AmtId(k)) - 0.5f) * 2f));+ }+ return l;+ }+ int FindCable(int s, int d) { foreach (var c in CableList()) if (c.Src == s && c.Dst == d) return c.Slot; return -1; }+ bool AddCable(int s, int d, float depth = 0.5f)+ {+ int slot = FindCable(s, d);+ if (slot >= 0) { SetP(AmtId(slot), 0.5f + depth / 2); Refresh(); return true; }+ var used = CableList().Select(c => c.Slot).ToHashSet();+ for (int k = 0; k < Cables; k++)+ {+ if (used.Contains(k)) continue;+ SetP(SrcId(k), ConsortJacks.ToNorm(s)); SetP(DstId(k), ConsortJacks.ToNorm(d)); SetP(AmtId(k), 0.5f + depth / 2);+ Refresh(); return true;+ }+ return false; // all twelve slots in use+ }+ void RemoveSlot(int k) { SetP(SrcId(k), 0f); SetP(DstId(k), 0f); SetP(AmtId(k), 0.75f); Refresh(); }+ void RemoveAtJack(ConsortJacks.Jack j) { foreach (var c in CableList()) if (j.Out ? c.Src == j.Index : c.Dst == j.Index) RemoveSlot(c.Slot); }+ void ClearAll() { foreach (var c in CableList()) RemoveSlot(c.Slot); }+ IBrush? PatchedAt(bool isOut, params int[] jacks)+ {+ foreach (var c in CableList())+ if (isOut ? jacks.Contains(c.Src) : jacks.Contains(c.Dst)) return ConsortJacks.ToneBrush(ConsortJacks.Src(c.Src).Tone);+ return null;+ }+ string CableName(ConsortCable c) => $"{ConsortJacks.Src(c.Src).Name} → {ConsortJacks.Dst(c.Dst).Name}";+ string CableChip(ConsortCable c) => $"{SrcChip[Math.Min(c.Src, SrcChip.Length - 1)]}→{DstChip[Math.Min(c.Dst, DstChip.Length - 1)]}";++ // Right-click / click on a jack: its cables (remove) + quick patch to any opposite jack.+ void JackMenu(ConsortJacks.Jack j, Control anchor)+ {+ var f = new MenuFlyout();+ f.Items.Add(new MenuItem { Header = $"{j.Name} · {(j.Out ? "output" : "input")}{(ConsortJacks.Normalled.Contains(j.Index) && !j.Out ? " (normalled)" : "")}", IsEnabled = false });+ var mine = CableList().Where(c => j.Out ? c.Src == j.Index : c.Dst == j.Index).ToList();+ foreach (var c in mine)+ {+ var mi = new MenuItem { Header = $"Remove {CableName(c)} {c.Depth * 100:+0;-0;0}" };+ int slot = c.Slot; mi.Click += (_, _) => RemoveSlot(slot);+ f.Items.Add(mi);+ }+ var sub = new MenuItem { Header = j.Out ? "Patch to" : "Patch from" };+ var list = j.Out ? ConsortJacks.Dests : ConsortJacks.Sources;+ for (int i = 1; i < list.Length; i++)+ {+ var o = list[i];+ var mi = new MenuItem { Header = o.Name };+ mi.Click += (_, _) => { if (j.Out) AddCable(j.Index, o.Index); else AddCable(o.Index, j.Index); };+ sub.Items.Add(mi);+ }+ f.Items.Add(sub);+ f.ShowAt(anchor, showAtPointer: true);+ }++ // ======================================================================+ // LEFT — wheels+ // ======================================================================+ var bendTxt = MonoText("", 7, AmberLit); var modTxt = MonoText("", 7, MutedC);+ bendTxt.HorizontalAlignment = HorizontalAlignment.Center; modTxt.HorizontalAlignment = HorizontalAlignment.Center;+ common.Add(() => { bendTxt.Text = $"±{BendSt()} st"; modTxt.Text = $"{G("modwheel") * 100:0} %"; modTxt.Foreground = G("modwheel") > 0.01f ? AmberLit : MutedC; });+ var wheelsBody = new DockPanel { LastChildFill = true };+ var wTitle = Caps("WHEELS"); wTitle.HorizontalAlignment = HorizontalAlignment.Center; wTitle.Margin = new Thickness(0, 0, 0, 4);+ wheelsBody.Children.Add(Docked(wTitle, Avalonia.Controls.Dock.Top));+ wheelsBody.Children.Add(Docked(modTxt, Avalonia.Controls.Dock.Bottom));+ wheelsBody.Children.Add(Docked(bendTxt, Avalonia.Controls.Dock.Bottom));+ wheelsBody.Children.Add(new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 0, 0, 3), Children = {+ VWheel("bend", "PIT", Amber, spring: true),+ VWheel("modwheel", "MOD", AmberLit, spring: false) } });+ var wheels = new Border { Width = 52, Background = Panel, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(5), Padding = new Thickness(0, 5), Child = wheelsBody };+ DockPanel.SetDock(wheels, Avalonia.Controls.Dock.Left);++ // ======================================================================+ // CENTRE — Osc · Mix+ // ======================================================================+ const string OscCols = "14,54,70,*,74";+ Control Cell(Control c, int col, HorizontalAlignment ha = HorizontalAlignment.Center) { c.HorizontalAlignment = ha; c.VerticalAlignment = VerticalAlignment.Center; return Col(new Panel { Children = { c } }, col); }+ Control WaveSel(string id)+ {+ int[] icon = { 2, 0, 3, 1 }; // triangle, saw, square, pulse (PentadWaveIcon glyphs)+ string[] tip = { "Triangle", "Saw", "Square", "Pulse (width = PWM)" };+ var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3 };+ var chips = new Border[4]; var icons = new PentadWaveIcon[4];+ for (int w = 0; w < 4; w++)+ {+ int wv = w;+ var ic = new PentadWaveIcon(icon[w]) { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ var b = new Border { Width = 24, Height = 16, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(3), Cursor = new Cursor(StandardCursorType.Hand), Child = ic };+ ToolTip.SetTip(b, tip[w]);+ b.PointerPressed += (_, e) => { SetP(id, wv / 3f); Refresh(); e.Handled = true; };+ chips[w] = b; icons[w] = ic; row.Children.Add(b);+ }+ cur.Add(() =>+ {+ int s = Sel(id, 4);+ for (int w = 0; w < 4; w++) { bool on = w == s; chips[w].Background = on ? AmberSubtle : Brushes.Transparent; chips[w].BorderBrush = on ? Amber : NotaPalette.BorderStrong; icons[w].Stroke = on ? AmberLit : MutedC; icons[w].InvalidateVisual(); }+ });+ if (I(id) is var pi and >= 0) MidiLearn.Bind(row, MidiTarget.PluginParam(track, -1, pi), id);+ return row;+ }+ Control SyncChip(string id, string text)+ {+ var tb = MonoText(text, 8, MutedC);+ var b = new Border { Padding = new Thickness(4, 1), CornerRadius = new CornerRadius(3), BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), Child = tb };+ ToolTip.SetTip(b, "Hard sync");+ b.PointerPressed += (_, e) => { SetP(id, On(id) ? 0f : 1f); Refresh(); e.Handled = true; };+ cur.Add(() => { bool on = On(id); tb.Foreground = on ? AmberLit : DimC; b.BorderBrush = on ? NotaPalette.AccentSubtle : Brushes.Transparent; b.Background = on ? AmberSubtle : Brushes.Transparent; });+ if (I(id) is var pi and >= 0) MidiLearn.Bind(b, MidiTarget.PluginParam(track, -1, pi), id);+ return b;+ }+ Control OscRow(int n)+ {+ string p = $"o{n}";+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions(OscCols) };+ g.Children.Add(Cell(Lbl(n.ToString(), 10, TxtC, FontWeight.SemiBold), 0, HorizontalAlignment.Left));+ g.Children.Add(Cell(MiniKnob($"{p}oct", Foot, 20, 26, AmberLit), 1, HorizontalAlignment.Left));+ g.Children.Add(n == 1 ? Cell(MonoText("master", 8, MutedC), 2, HorizontalAlignment.Left) : Cell(MiniKnob($"{p}freq", Freq, 20, 40, TxtC), 2, HorizontalAlignment.Left));+ g.Children.Add(Cell(WaveSel($"{p}wave"), 3));+ var jd = new ConsortJackDot(11);+ ToolTip.SetTip(jd, $"Osc {n} pitch input (patch bay)");+ cur.Add(() => jd.Set(PatchedAt(false, 4 + n, 4)));+ Control right = n == 2 ? SyncChip("o2sync", "sync→1") : n == 4 ? SyncChip("o4sync", "sync→3") : MonoText("—", 8, DimC);+ g.Children.Add(Cell(Row(5, jd, right), 4, HorizontalAlignment.Right));+ return new Border { BorderBrush = BorderIn, BorderThickness = new Thickness(0, 1, 0, 0), Child = g };+ }+ Control MixCell(string label, string id)+ {+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("32,*"), VerticalAlignment = VerticalAlignment.Center };+ g.Children.Add(Caps(label)); g.Children.Add(Col(HSlider(id, v => Tenths(v), 20), 1));+ return g;+ }+ Control OscTab()+ {+ var hdr = new Grid { ColumnDefinitions = new ColumnDefinitions(OscCols), Height = 13 };+ string[] h = { "#", "OCT", "FREQ", "WAVE", "SYNC / CV" };+ for (int i = 0; i < h.Length; i++)+ {+ var t = new TextBlock { Text = h[i], FontSize = 7, FontWeight = FontWeight.Bold, Foreground = DimC, LetterSpacing = 0.8, VerticalAlignment = VerticalAlignment.Center,+ HorizontalAlignment = i == 0 || i == 1 || i == 2 ? HorizontalAlignment.Left : i == h.Length - 1 ? HorizontalAlignment.Right : HorizontalAlignment.Center };+ hdr.Children.Add(Col(t, i));+ }+ var rows = new Grid { RowDefinitions = new RowDefinitions("*,*,*,*") };+ for (int n = 1; n <= 4; n++) rows.Children.Add(RowAt(OscRow(n), n - 1));+ var mix = new Grid { ColumnDefinitions = new ColumnDefinitions("38,*,*,*,Auto"), RowDefinitions = new RowDefinitions("*,*"), ColumnSpacing = 8, Height = 40 };+ mix.Children.Add(RowAt(Caps("MIXER"), 0)); Grid.SetRowSpan(mix.Children[^1], 2);+ mix.Children.Add(Col(MixCell("OSC 1", "mix1"), 1)); mix.Children.Add(RowAt(Col(MixCell("OSC 2", "mix2"), 1), 1));+ mix.Children.Add(Col(MixCell("OSC 3", "mix3"), 2)); mix.Children.Add(RowAt(Col(MixCell("OSC 4", "mix4"), 2), 1));+ mix.Children.Add(Col(MixCell("NOISE", "mixnoise"), 3)); mix.Children.Add(RowAt(Col(MixCell("EXT", "mixext"), 3), 1));+ var ext = mix.Children[^1]; ToolTip.SetTip(ext, "EXT: normalled to the VCA output (Moog feedback) — patch Ext in to replace it");+ mix.Children.Add(Col(Toggle("mixdrive", "Mixer drive"), 4));+ mix.Children.Add(RowAt(Col(Chips("noisecolor", new[] { "White", "Pink" }), 4), 1));+ return new DockPanel { LastChildFill = true, Margin = new Thickness(7, 0, 7, 3), Children = {+ Docked(hdr, Avalonia.Controls.Dock.Top),+ Docked(new Border { BorderBrush = BorderIn, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 3, 0, 0), Child = mix }, Avalonia.Controls.Dock.Bottom),+ rows } };+ }++ // ======================================================================+ // CENTRE — Filters · Env+ // ======================================================================+ Control FilterPanel()+ {+ var curve = new ConsortFilterCurve();+ curve.Changed = (c, r) => { Raw("cutoff", (float)c); Raw("reso", (float)r); Refresh(); };+ curve.DragStarted += () => { Begin("cutoff"); Begin("reso"); };+ curve.DragEnded += () => { End("cutoff"); End("reso"); };+ cur.Add(() => curve.Set(G("cutoff"), G("reso"), (G("spacing") - 0.5) * 6, Sel("filtmode", 3), On("basscomp")));+ var graph = new Border { Background = Inset, BorderBrush = BorderIn, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(4), Margin = new Thickness(0, 3, 0, 2), Child = curve };+ var head = new DockPanel { Height = 12, LastChildFill = false, Children = { Docked(Caps("DUAL LADDER"), Avalonia.Controls.Dock.Left), Docked(MonoText("24 dB/oct", 7, Txt2), Avalonia.Controls.Dock.Right) } };+ var knobs = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*,*") };+ knobs.Children.Add(K("cutoff", "CUTOFF", Cut, false, 28, 50));+ knobs.Children.Add(Col(K("reso", "RESON", v => Tenths(v), false, 28, 46), 1));+ knobs.Children.Add(Col(K("spacing", "SPACING", Space, false, 28, 50), 2));+ knobs.Children.Add(Col(K("fenvamt", "ENV AMT", EnvAmt, true, 28, 46), 3));+ var j1 = new ConsortJackDot(11); var j2 = new ConsortJackDot(11);+ ToolTip.SetTip(j1, "Filt 1 cutoff input"); ToolTip.SetTip(j2, "Filt 2 cutoff input");+ cur.Add(() => { j1.Set(PatchedAt(false, 10)); j2.Set(PatchedAt(false, 11)); });+ var bottom = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*,Auto"), ColumnSpacing = 8, Height = 18 };+ bottom.Children.Add(Row(5, Caps("KBD TRK"), Chips("kbdtrk", new[] { "0", "½", "1" })));+ bottom.Children.Add(Col(Toggle("basscomp", "Bass comp"), 1));+ bottom.Children.Add(Col(Row(4, j1, j2), 3));+ var body = new DockPanel { LastChildFill = true, Children = { Docked(head, Avalonia.Controls.Dock.Top), Docked(bottom, Avalonia.Controls.Dock.Bottom), Docked(knobs, Avalonia.Controls.Dock.Bottom), graph } };+ return new Border { Width = 222, BorderBrush = BorderIn, BorderThickness = new Thickness(0, 0, 1, 0), Padding = new Thickness(7, 4), Child = body };+ }+ Control EnvPanel(string title, string pre, bool amp)+ {+ var curve = new PentadEnvCurve { Accent = amp ? TealC : Amber };+ var times = MonoText("", 7, Txt2);+ cur.Add(() =>+ {+ curve.Set(G(pre + "attack"), G(pre + "decay"), G(pre + "sustain"), G(pre + "release")); curve.InvalidateVisual();+ times.Text = $"{Atk(G(pre + "attack"))} · {Dec(G(pre + "decay"))} · {G(pre + "sustain") * 100:0}% · {Dec(G(pre + "release"))}";+ });+ var head = new DockPanel { Height = 12, LastChildFill = false, Margin = new Thickness(0, 0, 0, 2) };+ head.Children.Add(Docked(Caps(title), Avalonia.Controls.Dock.Left));+ head.Children.Add(Docked(times, Avalonia.Controls.Dock.Right));+ var graph = new Border { Background = Inset, BorderBrush = BorderIn, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(4), Child = curve };+ var knobs = Row(0, K(pre + "attack", "A", Atk, amp, 22, 27), K(pre + "decay", "D", Dec, amp, 22, 27), K(pre + "sustain", "S", v => Pct(v), amp, 22, 27), K(pre + "release", "R", Dec, amp, 22, 27));+ knobs.Margin = new Thickness(4, 0, 0, 0);+ return new DockPanel { LastChildFill = true, Children = { Docked(head, Avalonia.Controls.Dock.Top), Docked(knobs, Avalonia.Controls.Dock.Right), graph } };+ }+ Control FilterEnvTab()+ {+ var envs = new Grid { RowDefinitions = new RowDefinitions("*,*"), Margin = new Thickness(7, 4) };+ var fe = EnvPanel("FILTER ENVELOPE", "f", false);+ var ae = Divider(EnvPanel("AMPLITUDE ENVELOPE", "a", true), 4); ae.Margin = new Thickness(0, 4, 0, 0); Grid.SetRow(ae, 1);+ envs.Children.Add(fe); envs.Children.Add(ae);+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*") };+ g.Children.Add(FilterPanel()); g.Children.Add(Col(envs, 1));+ return g;+ }++ // ======================================================================+ // CENTRE — LFO · Delay+ // ======================================================================+ Control LfoPanel()+ {+ var shapes = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3 };+ var chips = new Border[6]; var icons = new ConsortLfoIcon[6];+ for (int s = 0; s < 6; s++)+ {+ int sv = s;+ var ic = new ConsortLfoIcon(s) { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ var b = new Border { Width = 26, Height = 17, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(3), Cursor = new Cursor(StandardCursorType.Hand), Child = ic };+ ToolTip.SetTip(b, LfoNames[s]);+ b.PointerPressed += (_, e) => { SetP("lfowave", sv / 5f); Refresh(); e.Handled = true; };+ chips[s] = b; icons[s] = ic; shapes.Children.Add(b);+ }+ cur.Add(() => { int s = Sel("lfowave", 6); for (int i = 0; i < 6; i++) { bool on = i == s; chips[i].Background = on ? AmberSubtle : Brushes.Transparent; chips[i].BorderBrush = on ? Amber : NotaPalette.BorderStrong; icons[i].Stroke = on ? AmberLit : MutedC; icons[i].InvalidateVisual(); } });+ if (I("lfowave") is var pw and >= 0) MidiLearn.Bind(shapes, MidiTarget.PluginParam(track, -1, pw), "lfowave");+ var jo = new ConsortJackDot(12); var jr = new ConsortJackDot(12);+ ToolTip.SetTip(jo, "LFO out (patch bay)"); ToolTip.SetTip(jr, "LFO rate input (patch bay)");+ cur.Add(() => { jo.Set(PatchedAt(true, 1)); jr.Set(PatchedAt(false, 1)); });+ var head = new DockPanel { Height = 14, LastChildFill = false, Children = { Docked(Caps("LFO"), Avalonia.Controls.Dock.Left), Docked(Row(4, jo, jr), Avalonia.Controls.Dock.Right) } };+ var knobs = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*,*"), Margin = new Thickness(0, 4, 0, 0) };+ knobs.Children.Add(K("lforate", "RATE", LfoRate, true, 28, 44));+ knobs.Children.Add(Col(K("lfopitch", "PITCH", LfoCents, true, 28, 44), 1));+ knobs.Children.Add(Col(K("lfocut", "CUTOFF", v => Pct(v), true, 28, 44), 2));+ knobs.Children.Add(Col(K("lfopwm", "PWM", v => Pct(v), true, 28, 44), 3));+ var syncT = Toggle("lfosync", "Sync");+ var syncLbl = (TextBlock)((StackPanel)syncT).Children[1];+ cur.Add(() => syncLbl.Text = On("lfosync") ? $"Sync {SyncNames[Math.Clamp((int)Math.Round(G("lforate") * 13), 0, 13)]}" : "Sync");+ var bottom = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), Height = 18 };+ bottom.Children.Add(syncT); bottom.Children.Add(Col(Chips("lfodest", new[] { "All osc", "2 + 4" }), 1));+ ToolTip.SetTip(bottom.Children[1], "LFO pitch → all oscillators, or only 2 and 4");+ var body = new DockPanel { LastChildFill = false, Children = { Docked(head, Avalonia.Controls.Dock.Top), Docked(shapes, Avalonia.Controls.Dock.Top), Docked(knobs, Avalonia.Controls.Dock.Top), Docked(Divider(bottom, 4), Avalonia.Controls.Dock.Bottom) } };+ return new Border { Width = 196, BorderBrush = BorderIn, BorderThickness = new Thickness(0, 0, 1, 0), Padding = new Thickness(7, 4), Child = body };+ }+ Control DelayPanel()+ {+ var view = new ConsortDelayView();+ var times = MonoText("", 7, Txt2);+ cur.Add(() =>+ {+ double tl = DlySec(G("dlytime")), tr = Math.Clamp(tl + (G("dlyspacing") - 0.5), 0.005, 2.0);+ view.Set(tl, tr, G("dlyfb"), G("dlymix"), On("dlyping"), On("dlydigital"));+ times.Text = $"L {tl * 1000:0} · R {tr * 1000:0} ms";+ });+ var head = new DockPanel { Height = 14, LastChildFill = false, Children = { Docked(Caps(""), Avalonia.Controls.Dock.Left), Docked(times, Avalonia.Controls.Dock.Right) } };+ var title = (TextBlock)head.Children[0];+ cur.Add(() => title.Text = On("dlydigital") ? "DELAY · DIGITAL" : "ANALOG DELAY · BBD");+ var graph = new Border { Background = Inset, BorderBrush = BorderIn, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(4), Margin = new Thickness(0, 2, 0, 3), Child = view };+ var knobs = Row(0, K("dlytime", "TIME", DlyMs, false, 28, 44), K("dlyspacing", "SPACING", DlySpc, false, 28, 44), K("dlyfb", "FEEDBACK", v => Pct(v), false, 28, 46), K("dlymix", "MIX", v => Pct(v), false, 28, 40));+ var opts = new StackPanel { Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Children = { Chips("dlyping", new[] { "Ping", "Stereo" }, new[] { 1f, 0f }), Toggle("dlydigital", "Digital") } };+ var bottom = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*") };+ bottom.Children.Add(knobs); bottom.Children.Add(Col(Right(opts), 1));+ return new DockPanel { LastChildFill = true, Margin = new Thickness(7, 4), Children = { Docked(head, Avalonia.Controls.Dock.Top), Docked(bottom, Avalonia.Controls.Dock.Bottom), graph } };+ }+ Control LfoDelayTab()+ {+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*") };+ g.Children.Add(LfoPanel()); g.Children.Add(Col(DelayPanel(), 1));+ return g;+ }++ // ======================================================================+ // CENTRE — Seq+ // ======================================================================+ int[] StepTypes() { var t = new int[16]; for (int s = 0; s < 16; s++) t[s] = Math.Clamp((int)Math.Round(G($"st{s + 1}") * 3), 0, 3); return t; }+ int[] StepPitches() { var p = new int[16]; for (int s = 0; s < 16; s++) p[s] = Math.Clamp((int)Math.Round((G($"sp{s + 1}") - 0.5) * 48), -24, 24); return p; }+ int SeqLen() => 1 + Math.Clamp((int)Math.Round(G("seqlen") * 15), 0, 15);+ int Ratchet() => 2 + Math.Clamp((int)Math.Round(G("seqratchet") * 2), 0, 2);+ int PlayStep() => scN > 7 ? (int)scope[7] : -1;+ Control SeqTab()+ {+ // length: a draggable number+ var lenTxt = MonoText("", 9, AmberLit);+ var lenBox = new Border { Padding = new Thickness(3, 0), Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.SizeNorthSouth), Child = lenTxt };+ ToolTip.SetTip(lenBox, "Sequence length — drag up / down");+ { bool drag = false; double y0 = 0; float v0 = 0;+ lenBox.PointerPressed += (_, e) => { if (!e.GetCurrentPoint(lenBox).Properties.IsLeftButtonPressed) return; drag = true; y0 = e.GetPosition(lenBox).Y; v0 = G("seqlen"); Begin("seqlen"); e.Pointer.Capture(lenBox); e.Handled = true; };+ lenBox.PointerMoved += (_, e) => { if (!drag) return; float v = Math.Clamp(v0 + (float)(y0 - e.GetPosition(lenBox).Y) / 120f, 0, 1); v = (float)Math.Round(v * 15) / 15f; Raw("seqlen", v); Refresh(); };+ lenBox.PointerReleased += (_, e) => { if (drag) { drag = false; End("seqlen"); e.Pointer.Capture(null); } }; }+ tabReadouts[3].Add(() => lenTxt.Text = $"{SeqLen()}");+ // legend = paint brushes+ string[] names = { "note", "ratchet", "tie", "rest" };+ IBrush[] cols = { Amber, ChamberInk.Mauve, TealC, NotaPalette.BorderStrong };+ var legend = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 7, VerticalAlignment = VerticalAlignment.Center };+ var legItems = new Border[4];+ for (int b = 0; b < 4; b++)+ {+ int bv = b;+ var sw = new Border { Width = 9, Height = 9, CornerRadius = new CornerRadius(2), BorderBrush = cols[b], BorderThickness = new Thickness(1), Background = b == 3 ? Inset : new SolidColorBrush(((ISolidColorBrush)cols[b]).Color, 0.35) };+ var it = new Border { Background = Brushes.Transparent, Padding = new Thickness(3, 1), CornerRadius = new CornerRadius(3), BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), Child = Row(3, sw, new TextBlock { Text = names[b], FontSize = 8, Foreground = Txt2, VerticalAlignment = VerticalAlignment.Center }) };+ ToolTip.SetTip(it, $"Paint {names[b]} steps (Alt-click a step: rest)");+ it.PointerPressed += (_, e) => { vs.Brush = bv; Refresh(); e.Handled = true; };+ legItems[b] = it; legend.Children.Add(it);+ }+ tabReadouts[3].Add(() => { for (int b = 0; b < 4; b++) legItems[b].BorderBrush = b == vs.Brush ? NotaPalette.AccentSubtle : Brushes.Transparent; });+ List<Action> saved = cur; cur = tabReadouts[3];+ var ratchet = Chips("seqratchet", new[] { "×2", "×3", "×4" });+ ToolTip.SetTip(ratchet, "Ratchet repeats per step");+ var top = new DockPanel { Height = 16, LastChildFill = false };+ top.Children.Add(Docked(Row(4, Caps("STEPS"), lenBox, MonoText("/ 16", 8, MutedC)), Avalonia.Controls.Dock.Left));+ top.Children.Add(Docked(Row(8, legend, ratchet), Avalonia.Controls.Dock.Right));++ var grid = new ConsortStepGrid { Height = 24, Margin = new Thickness(0, 3, 0, 3) };+ var gestureIds = new HashSet<string>();+ grid.PaintStarted += () => gestureIds.Clear();+ grid.Paint += (s, erase) =>+ {+ string id = $"st{s + 1}";+ if (gestureIds.Add(id)) Begin(id);+ int t = erase ? 3 : vs.Brush;+ Raw(id, t / 3f); Refresh();+ };+ grid.PaintEnded += () => { foreach (var id in gestureIds) End(id); gestureIds.Clear(); };+ var lane = new ConsortPitchLane();+ lane.DragStarted += s => Begin($"sp{s + 1}");+ lane.DragEnded += s => End($"sp{s + 1}");+ lane.PitchChanged += (s, v) => { Raw($"sp{s + 1}", 0.5f + v / 48f); Refresh(); };+ tabReadouts[3].Add(() =>+ {+ var types = StepTypes();+ grid.Set(types, SeqLen(), PlayStep(), Ratchet());+ lane.Set(StepPitches(), types, SeqLen(), PlayStep(), Sel("seqmode", 3) == 2);+ });+ var laneBox = new Border { Background = Inset, BorderBrush = BorderIn, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(4), Child = lane };++ var clkDot = new ConsortJackDot(12); var gateDot = new ConsortJackDot(12);+ ToolTip.SetTip(clkDot, "Clock out (patch bay)"); ToolTip.SetTip(gateDot, "Seq gate out (patch bay)");+ tabReadouts[3].Add(() => { clkDot.Set(PatchedAt(true, 12)); gateDot.Set(PatchedAt(true, 11, 10)); });+ var swingSl = HSlider("seqswing", v => $"{50 + v * 25:0} %", 28); swingSl.Width = 84;+ var rateTxt = MonoText("", 9, AmberLit);+ var rateBox = new Border { Background = Brushes.Transparent, Padding = new Thickness(2, 0), Cursor = new Cursor(StandardCursorType.Hand), Child = rateTxt };+ ToolTip.SetTip(rateBox, "Step rate (synced to the host tempo)");+ tabReadouts[3].Add(() => rateTxt.Text = SeqRates[Sel("seqrate", SeqRates.Length)] + " ▾");+ rateBox.PointerPressed += (_, e) =>+ {+ var f = new MenuFlyout();+ for (int r = 0; r < SeqRates.Length; r++) { int rv = r; var mi = new MenuItem { Header = SeqRates[r] }; mi.Click += (_, _) => { SetP("seqrate", rv / (float)(SeqRates.Length - 1)); Refresh(); }; f.Items.Add(mi); }+ f.ShowAt(rateBox); e.Handled = true;+ };+ if (I("seqrate") is var ri and >= 0) MidiLearn.Bind(rateBox, MidiTarget.PluginParam(track, -1, ri), "seqrate");+ var bottom = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 11, Height = 20, Children = {+ Row(4, Caps("RATE"), rateBox),+ Row(4, Caps("SWING"), swingSl),+ Row(4, Caps("ORDER"), Chips("seqorder", new[] { "Fwd", "Back", "Rnd" })),+ Toggle("seqlatch", "Latch"),+ Row(4, Caps("CLK"), gateDot, clkDot) } };+ cur = saved;+ return new DockPanel { LastChildFill = true, Margin = new Thickness(7, 3, 7, 2), Children = {+ Docked(top, Avalonia.Controls.Dock.Top), Docked(grid, Avalonia.Controls.Dock.Top),+ Docked(new Border { Padding = new Thickness(0, 3, 0, 0), Child = bottom }, Avalonia.Controls.Dock.Bottom),+ laneBox } };+ }++ // ======================================================================+ // CENTRE — Patch (matrix / jack strip)+ // ======================================================================+ int[] MatrixRows()+ {+ var l = new List<int>();+ foreach (var c in CableList()) if (!l.Contains(c.Src) && l.Count < 5) l.Add(c.Src);+ foreach (var p in vs.RowPrefs) if (!l.Contains(p) && l.Count < 5) l.Add(p);+ return l.ToArray();+ }+ int[] MatrixCols()+ {+ var l = new List<int>();+ foreach (var c in CableList()) if (!l.Contains(c.Dst) && l.Count < 5) l.Add(c.Dst);+ foreach (var p in vs.ColPrefs) if (!l.Contains(p) && l.Count < 5) l.Add(p);+ return l.ToArray();+ }+ Control MatrixView()+ {+ var m = new ConsortPatchMatrix();+ string? gest = null;+ m.GestureBegin += (s, d) => { int k = FindCable(s, d); if (k >= 0) { gest = AmtId(k); Begin(gest); } };+ m.GestureEnd += (s, d) => { if (gest != null) End(gest); gest = null; };+ m.DepthChanged += (s, d, v) =>+ {+ int k = FindCable(s, d);+ if (k < 0) { if (AddCable(s, d, v)) { k = FindCable(s, d); if (k >= 0) { gest = AmtId(k); Begin(gest); } } return; }+ Raw(AmtId(k), 0.5f + v / 2); Refresh();+ };+ m.Removed += (s, d) => { int k = FindCable(s, d); if (k >= 0) RemoveSlot(k); };+ m.HeaderClicked += (isRow, i, rect) =>+ {+ var f = new MenuFlyout();+ var list = isRow ? ConsortJacks.Sources : ConsortJacks.Dests;+ for (int j = 1; j < list.Length; j++)+ {+ int jv = j;+ var mi = new MenuItem { Header = list[j].Name };+ mi.Click += (_, _) => { var prefs = isRow ? vs.RowPrefs : vs.ColPrefs; prefs.Remove(jv); prefs.Insert(0, jv); Refresh(); };+ f.Items.Add(mi);+ }+ f.ShowAt(m, showAtPointer: true);+ };+ tabReadouts[4].Add(() => m.Set(MatrixRows(), MatrixCols(), CableList()));+ List<Action> saved = cur; cur = tabReadouts[4];+ var a1 = HSlider("atten1", v => Depth(v), 26, null, true); a1.Width = 70;+ var a2 = HSlider("atten2", v => Depth(v), 26, null, true); a2.Width = 70;+ cur = saved;+ var si = new ConsortJackDot(12); var so = new ConsortJackDot(12);+ ToolTip.SetTip(si, "Sum in"); ToolTip.SetTip(so, "Sum out");+ tabReadouts[4].Add(() => { si.Set(PatchedAt(false, 22)); so.Set(PatchedAt(true, 20)); });+ var util = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, Height = 20, Children = {+ Caps("UTIL"), Row(5, Caps("ATTEN 1"), a1), Row(5, Caps("ATTEN 2"), a2), Row(4, Caps("SUM"), si, so) } };+ ToolTip.SetTip(util, "Attenuators scale whatever is patched into Atten 1/2 in; Sum adds its inputs");+ return new DockPanel { LastChildFill = true, Children = { Docked(Divider(util, 3), Avalonia.Controls.Dock.Bottom), m } };+ }+ Control CableListView(List<Action> into)+ {+ var host = new StackPanel { Spacing = 3 };+ var rowReadouts = new List<Action>();+ string? sig = null;+ void Rebuild()+ {+ host.Children.Clear(); rowReadouts.Clear();+ var cs = CableList();+ if (cs.Count == 0) host.Children.Add(new TextBlock { Text = "No cables", FontSize = 8, Foreground = DimC });+ foreach (var c in cs)+ {+ int slot = c.Slot;+ var dot = new Border { Width = 6, Height = 6, CornerRadius = new CornerRadius(3), Background = ConsortJacks.ToneBrush(ConsortJacks.Src(c.Src).Tone), VerticalAlignment = VerticalAlignment.Center };+ var x = new TextBlock { Text = "✕", FontSize = 8, Foreground = MutedC, Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center };+ x.PointerPressed += (_, e) => { RemoveSlot(slot); e.Handled = true; };+ var name = new TextBlock { Text = $"{ConsortJacks.ShortName(ConsortJacks.Src(c.Src).Name)} → {ConsortJacks.ShortName(ConsortJacks.Dst(c.Dst).Name)}", FontSize = 8.5, Foreground = TxtC, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };+ var hdr = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 5 };+ hdr.Children.Add(dot); hdr.Children.Add(Col(name, 1)); hdr.Children.Add(Col(x, 2));+ List<Action> saved = cur; cur = rowReadouts;+ var sl = HSlider(AmtId(slot), v => Depth(v), 24, null, true);+ cur = saved;+ var dep = new Grid { ColumnDefinitions = new ColumnDefinitions("34,*") };+ dep.Children.Add(Caps("DEPTH")); dep.Children.Add(Col(sl, 1));+ host.Children.Add(new Border { BorderBrush = BorderIn, BorderThickness = new Thickness(0, 0, 0, 1), Padding = new Thickness(0, 1, 0, 3), Child = new StackPanel { Spacing = 2, Children = { hdr, dep } } });+ }+ }+ into.Add(() =>+ {+ string s = string.Join(",", CableList().Select(c => $"{c.Slot}:{c.Src}:{c.Dst}"));+ if (s != sig) { sig = s; Rebuild(); }+ foreach (var a in rowReadouts) a();+ });+ return new ScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled, Content = host };+ }+ ConsortJackField StripField()+ {+ ConsortJacks.Jack S(int i) => ConsortJacks.Sources[i];+ ConsortJacks.Jack D(int i) => ConsortJacks.Dests[i];+ var rows = new List<List<ConsortJackField.Group>>+ {+ new() { new("LFO", new[] { S(1), D(1) }), new("ENV", new[] { S(2), S(3), D(2), D(3) }), new("OSC OUT", new[] { S(4), S(5), S(6), S(7), S(8) }), new("SEQ", new[] { S(10), S(11), S(12) }) },+ new() { new("OSC IN", new[] { D(4), D(5), D(6), D(7), D(8), D(9) }), new("FILTER", new[] { D(10), D(11), D(12), D(13), S(9) }), new("VCA", new[] { D(14), D(15), D(19) }) },+ new() { new("DELAY", new[] { D(16), D(17), D(18) }), new("KBD", new[] { S(13), S(14), S(15), S(16), S(17) }), new("UTIL", new[] { D(20), S(18), D(21), S(19), D(22), S(20) }) },+ };+ var f = new ConsortJackField(rows, false);+ f.Connect += (s, d) => AddCable(s, d);+ f.Pull += RemoveAtJack;+ f.Context += JackMenu;+ return f;+ }+ Control CablesView()+ {+ var field = StripField();+ tabReadouts[4].Add(() => field.SetCables(CableList()));+ var list = CableListView(tabReadouts[4]);+ var hint = new TextBlock { Text = "Drag jack to jack · Alt-click to pull · right-click for a list", FontSize = 7.5, Foreground = DimC, TextWrapping = TextWrapping.Wrap };+ var side = new DockPanel { LastChildFill = true, Children = { Docked(new Border { Margin = new Thickness(0, 0, 0, 3), Child = Caps("CABLES") }, Avalonia.Controls.Dock.Top), Docked(hint, Avalonia.Controls.Dock.Bottom), list } };+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,144") };+ g.Children.Add(new Border { Padding = new Thickness(2, 2, 4, 0), Child = field });+ g.Children.Add(Col(new Border { BorderBrush = BorderIn, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(7, 3, 0, 2), Child = side }, 1));+ return g;+ }+ Control PatchTab()+ {+ var host = new ContentControl();+ Control? mat = null, cab = null;+ void Show() { host.Content = vs.PatchView == 0 ? (mat ??= MatrixView()) : (cab ??= CablesView()); Refresh(); }+ patchShow = Show;+ Show();+ return new Border { Padding = new Thickness(7, 3, 7, 2), Child = host };+ }++ // ======================================================================+ // RIGHT — Voices / Output+ // ======================================================================+ bool Poly() => On("truepoly");+ Control VoicesTab()+ {+ var cells = new Border[4]; var txt = new TextBlock[4];+ var cellRow = new UniformGrid { Rows = 1, Columns = 4 };+ for (int i = 0; i < 4; i++)+ {+ txt[i] = MonoText("—", 8, DimC); txt[i].HorizontalAlignment = HorizontalAlignment.Center;+ cells[i] = new Border { Height = 18, Margin = new Thickness(1.5, 0), CornerRadius = new CornerRadius(3), BorderThickness = new Thickness(1), Child = txt[i] };+ ToolTip.SetTip(cells[i], $"Oscillator {i + 1}'s note (paraphonic) · the latest voices in true poly");+ cellRow.Children.Add(cells[i]);+ }+ rightReadouts[0].Add(() =>+ {+ for (int i = 0; i < 4; i++)+ {+ int note = scN > 12 + i ? (int)scope[12 + i] : -1;+ float lv = scN > 16 + i ? scope[16 + i] : 0;+ bool on = note >= 0;+ txt[i].Text = on ? NoteName(note) : "—"; txt[i].Foreground = on ? (lv > 0.01f ? AmberLit : Txt2) : DimC;+ cells[i].BorderBrush = on && lv > 0.01f ? Amber : NotaPalette.BorderStrong;+ cells[i].Background = on && lv > 0.01f ? AmberSubtle : Brushes.Transparent;+ }+ });+ var gated = MonoText("gated", 8, DimC);+ var gatedBox = new Border { Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Child = gated, HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center };+ ToolTip.SetTip(gatedBox, "Gated glide: only between overlapping (legato) notes");+ gatedBox.PointerPressed += (_, e) => { SetP("glidegated", On("glidegated") ? 0 : 1); Refresh(); e.Handled = true; };+ rightReadouts[0].Add(() => gated.Foreground = On("glidegated") ? AmberLit : DimC);+ Control Line(string cap, Control c, Control? right = null)+ {+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("46,*,Auto"), Height = 20 };+ g.Children.Add(Caps(cap)); g.Children.Add(Col(c, 1)); if (right != null) g.Children.Add(Col(right, 2));+ return g;+ }+ var mode = Chips("voicemode", new[] { "MONO", "DUO", "PARA" }, null, 7, Poly);+ var body = new StackPanel { Spacing = 1, Children = {+ Line("MODE", mode),+ Line("VOICES", cellRow),+ Line("GLIDE", HSlider("glide", v => GlideF(v), 38)),+ Line("TYPE", Chips("glidetype", new[] { "LCR", "LCT", "EXP" }), gatedBox),+ new Border { Height = 1, Background = BorderIn, Margin = new Thickness(0, 3) },+ new StackPanel { Spacing = 4, Margin = new Thickness(0, 2), Children = { Toggle("multitrig", "Multi trig", Poly), Toggle("truepoly", "True poly (16)"), Toggle("unison", "Unison detune") } },+ new Border { Height = 1, Background = BorderIn, Margin = new Thickness(0, 3) },+ Line("DRIFT", HSlider("drift", v => Pct(v), 30)) } };+ return new Border { Padding = new Thickness(8, 5), Child = body };+ }+ Control OutputTab()+ {+ var meterL = new PentadLevelBar { Vertical = true, Width = 11, Height = 56 };+ var meterR = new PentadLevelBar { Vertical = true, Width = 11, Height = 56 };+ rightReadouts[1].Add(() => { if (scN > 3) { meterL.SetLinear(scope[2]); meterR.SetLinear(scope[3]); } });+ var scale = new Grid { RowDefinitions = new RowDefinitions("*,*,*"), Height = 56, Children = {+ MonoText("0", 7, DimC), RowAt(MonoText("−12", 7, DimC), 1), RowAt(MonoText("−48", 7, DimC), 2) } };+ var meters = Row(4, new StackPanel { Spacing = 2, Children = { meterL, Center(Lbl("L", 7, MutedC, FontWeight.Normal)) } },+ new StackPanel { Spacing = 2, Children = { meterR, Center(Lbl("R", 7, MutedC, FontWeight.Normal)) } }, scale);+ meters.VerticalAlignment = VerticalAlignment.Top;+ var top = Row(12, K("volume", "VOLUME", VolDb, false, 40, 56), meters);+ var body = new DockPanel { LastChildFill = false, Children = {+ Docked(top, Avalonia.Controls.Dock.Top),+ Docked(Divider(new StackPanel { Spacing = 4, Children = {+ SliderRow("TUNE", "tune", v => Tune(v), 40, 34, null, true),+ SliderRow("BEND", "bendrange", v => $"±{1 + Math.Clamp((int)Math.Round(v * 11), 0, 11)} st", 40, 34),+ Toggle("velvca", "Velocity → VCA"),+ Toggle("atcut", "Aftertouch → cut") } }), Avalonia.Controls.Dock.Top),+ Docked(Divider(Row(8, Caps("OVERSAMPLE"), Chips("oversample", new[] { "×1", "×2", "×4" }))), Avalonia.Controls.Dock.Bottom) } };+ ((Control)body.Children[1]).Margin = new Thickness(0, 5, 0, 0);+ return new Border { Padding = new Thickness(8, 5), Child = body };+ }++ // ======================================================================+ // Tab frames + extras+ // ======================================================================+ var centreHost = new ContentControl();+ var rightHost = new ContentControl();+ var extrasHost = new ContentControl { VerticalAlignment = VerticalAlignment.Center };+ var tabBodies = new Control?[5]; var rightBodies = new Control?[2];+ var patchCountTxt = MonoText("", 8, Txt2);+ Control[] extras = new Control[5];+ {+ List<Action> saved = cur;+ cur = tabReadouts[0];+ var pwSl = HSlider("pw", v => Pct(v), 26); pwSl.Width = 84;+ extras[0] = Row(6, Caps("PWM"), pwSl);+ ToolTip.SetTip(extras[0], "Pulse width of the pulse wave (square stays 50 %)");+ cur = tabReadouts[1];+ extras[1] = Chips("filtmode", new[] { "HP/LP ser", "LP/LP st", "HP/LP st" });+ cur = tabReadouts[2];+ var dlyTxt = MonoText("", 7.5, MutedC);+ tabReadouts[2].Add(() => dlyTxt.Text = $"{(On("dlydigital") ? "digital" : "BBD")} · {(On("dlyping") ? "ping-pong" : "stereo")}");+ extras[2] = dlyTxt;+ cur = tabReadouts[3];+ extras[3] = Row(6, Chips("seqmode", new[] { "Off", "SEQ", "ARP" }), Caps("OCT"), Chips("arpoct", new[] { "1", "2", "3" }, null, 7, () => Sel("seqmode", 3) != 2));+ ToolTip.SetTip(extras[3], "Off · SEQ (steps transposed by the key) · ARP (the held chord over 1–3 octaves)");+ cur = saved;+ extras[4] = Row(6, ViewSeg(new[] { "Matrix", "Cables" }, () => vs.PatchView, v => { vs.PatchView = v; patchShow(); }), patchCountTxt);+ common.Add(() => patchCountTxt.Text = $"{CableList().Count} / {Cables}");+ }+ Control CentreBody(int t)+ {+ if (tabBodies[t] != null) return tabBodies[t]!;+ List<Action> saved = cur; cur = tabReadouts[t];+ var b = t switch { 1 => FilterEnvTab(), 2 => LfoDelayTab(), 3 => SeqTab(), 4 => PatchTab(), _ => OscTab() };+ cur = saved;+ return tabBodies[t] = b;+ }+ Control RightBody(int t)+ {+ if (rightBodies[t] != null) return rightBodies[t]!;+ List<Action> saved = cur; cur = rightReadouts[t];+ var b = t == 1 ? OutputTab() : VoicesTab();+ cur = saved;+ return rightBodies[t] = b;+ }++ var (centre, selectCentre) = TabFrame(new[] { "Osc · Mix", "Filters · Env", "LFO · Delay", "Seq", "Patch" }, centreHost, CentreBody, false, vs.Centre,+ t => { vs.Centre = t; if (t != 4) vs.LastNonPatch = t; extrasHost.Content = extras[t]; Refresh(); }, extrasHost);+ var (rightFrame, _) = TabFrame(new[] { "Voices", "Output" }, rightHost, RightBody, true, vs.Right, t => { vs.Right = t; Refresh(); }, null);+ var right = new Border { Width = 172, Background = Panel, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(5), Child = rightFrame };+ DockPanel.SetDock(right, Avalonia.Controls.Dock.Right);+ var centreBox = new Border { Background = Panel, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(5), Margin = new Thickness(5, 0), Child = centre };++ // ======================================================================+ // Patch-bay row (collapsed) + overlay+ // ======================================================================+ var overlay = new Border { IsVisible = false, Background = RailBg, Focusable = true };+ void OpenOverlay(bool open) { vs.Overlay = open; overlay.IsVisible = open; if (open) { overlay.Focus(); } Refresh(); }+ var chipsHost = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 9, VerticalAlignment = VerticalAlignment.Center, ClipToBounds = true };+ var countTxt = MonoText("", 8, AmberLit);+ var openTxt = new TextBlock { FontSize = 8, Foreground = TxtC, VerticalAlignment = VerticalAlignment.Center };+ var openBtn = new Border { Height = 13, Padding = new Thickness(6, 0), CornerRadius = new CornerRadius(3), Background = OffPill, BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = openTxt };+ ToolTip.SetTip(openBtn, "Open the full patch bay (all 42 points) · on the Patch tab: back to the last panel");+ openBtn.PointerPressed += (_, e) =>+ {+ if (vs.Centre == 4) selectCentre(vs.LastNonPatch);+ else OpenOverlay(true);+ e.Handled = true;+ };+ string? stripSig = null;+ common.Add(() =>+ {+ var cs = CableList();+ string s = string.Join(",", cs.Select(c => $"{c.Src}:{c.Dst}"));+ if (s != stripSig)+ {+ stripSig = s;+ chipsHost.Children.Clear();+ foreach (var c in cs)+ {+ var chip = Row(3, new Border { Width = 6, Height = 6, CornerRadius = new CornerRadius(3), Background = ConsortJacks.ToneBrush(ConsortJacks.Src(c.Src).Tone), VerticalAlignment = VerticalAlignment.Center },+ MonoText(CableChip(c), 8, Txt2));+ chip.Background = Brushes.Transparent; chip.Cursor = new Cursor(StandardCursorType.Hand);+ ToolTip.SetTip(chip, $"{CableName(c)} · depth {c.Depth * 100:+0;-0;0}");+ chip.PointerPressed += (_, e) => { selectCentre(4); e.Handled = true; };+ chipsHost.Children.Add(chip);+ }+ if (cs.Count == 0) chipsHost.Children.Add(MonoText("no cables — the normals run the voice", 8, DimC));+ }+ countTxt.Text = cs.Count == 1 ? "1 cable" : $"{cs.Count} cables";+ bool onPatch = vs.Centre == 4;+ openTxt.Text = onPatch ? "Collapse ⌃" : "Open ⌄";+ openBtn.BorderBrush = onPatch ? Amber : Brushes.Transparent;+ });+ var stripGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto,Auto"), ColumnSpacing = 8 };+ stripGrid.Children.Add(Caps("PATCH BAY")); stripGrid.Children.Add(Col(chipsHost, 1)); stripGrid.Children.Add(Col(countTxt, 2)); stripGrid.Children.Add(Col(openBtn, 3));+ var strip = new Border { Height = 16, Background = RailBg, BorderBrush = Border2, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(8, 0), Child = stripGrid };+ DockPanel.SetDock(strip, Avalonia.Controls.Dock.Bottom);++ Control OverlayBody()+ {+ ConsortJacks.Jack S(int i) => ConsortJacks.Sources[i];+ ConsortJacks.Jack D(int i) => ConsortJacks.Dests[i];+ var cols = new List<List<ConsortJackField.Group>>+ {+ new() { new("MODULATION", new[] { S(1), D(1), S(2), S(3), D(2), D(3), S(17), S(16) }) },+ new() { new("OSCILLATORS", new[] { D(4), D(5), D(6), D(7), D(8), D(9), S(4), S(5), S(6), S(7) }) },+ new() { new("FILTERS / VCA", new[] { D(10), D(11), D(12), D(13), S(9), D(14), D(15), D(19) }) },+ new() { new("DELAY / SEQ", new[] { D(16), D(17), D(18), S(10), S(11), S(12) }) },+ new() { new("KBD / UTIL", new[] { S(13), S(14), S(15), S(8), D(20), S(18), D(21), S(19), D(22), S(20) }) },+ };+ var field = new ConsortJackField(cols, true);+ field.Connect += (s, d) => AddCable(s, d);+ field.Pull += RemoveAtJack;+ field.Context += JackMenu;+ overlayReadouts.Add(() => field.SetCables(CableList()));+ var info = MonoText("", 8, Txt2);+ overlayReadouts.Add(() => info.Text = $"{CableList().Count} cables · {ConsortJacks.Points} points");+ Border Btn(string t, Action a)+ {+ var b = new Border { Height = 16, Padding = new Thickness(7, 0), CornerRadius = new CornerRadius(3), Background = OffPill, Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = new TextBlock { Text = t, FontSize = 8.5, Foreground = TxtC, VerticalAlignment = VerticalAlignment.Center } };+ b.PointerPressed += (_, e) => { a(); e.Handled = true; };+ return b;+ }+ var view = ViewSeg(new[] { "Cables", "Matrix" }, () => 0, v => { if (v == 1) { vs.PatchView = 0; OpenOverlay(false); selectCentre(4); patchShow(); } });+ var topGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,*,Auto,Auto"), ColumnSpacing = 10 };+ topGrid.Children.Add(Lbl("Patch bay", 10, AmberLit, FontWeight.SemiBold));+ topGrid.Children.Add(Col(info, 1)); topGrid.Children.Add(Col(view, 2));+ topGrid.Children.Add(Col(Btn("Clear all", ClearAll), 4)); topGrid.Children.Add(Col(Btn("Esc ✕", () => OpenOverlay(false)), 5));+ var top = new Border { Height = 26, BorderBrush = Border2, BorderThickness = new Thickness(0, 0, 0, 1), Padding = new Thickness(10, 0), Child = topGrid };+ // bottom: cable list with draggable depths+ var bottomHost = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12, VerticalAlignment = VerticalAlignment.Center };+ string? sig = null;+ overlayReadouts.Add(() =>+ {+ var cs = CableList();+ string s = string.Join(",", cs.Select(c => $"{c.Slot}:{c.Src}:{c.Dst}:{c.Depth:0.00}"));+ if (s == sig) return;+ sig = s; bottomHost.Children.Clear();+ foreach (var c in cs)+ {+ int slot = c.Slot;+ var tone = ConsortJacks.ToneBrush(ConsortJacks.Src(c.Src).Tone);+ var dep = MonoText($"{c.Depth * 100:+0;-0;0}", 8, tone);+ var depBox = new Border { Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.SizeNorthSouth), Child = dep };+ ToolTip.SetTip(depBox, "Depth — drag up / down (double-click: +50)");+ bool drag = false; double y0 = 0; float v0 = 0;+ depBox.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(depBox).Properties.IsLeftButtonPressed) return;+ if (e.ClickCount == 2) { SetP(AmtId(slot), 0.75f); Refresh(); e.Handled = true; return; }+ drag = true; y0 = e.GetPosition(depBox).Y; v0 = G(AmtId(slot)); Begin(AmtId(slot)); e.Pointer.Capture(depBox); e.Handled = true;+ };+ depBox.PointerMoved += (_, e) => { if (!drag) return; float v = Math.Clamp(v0 + (float)(y0 - e.GetPosition(depBox).Y) / 200f, 0, 1); Raw(AmtId(slot), v); dep.Text = $"{(v - 0.5f) * 200:+0;-0;0}"; };+ depBox.PointerReleased += (_, e) => { if (drag) { drag = false; End(AmtId(slot)); e.Pointer.Capture(null); Refresh(); } };+ bottomHost.Children.Add(Row(4, new Border { Width = 7, Height = 7, CornerRadius = new CornerRadius(4), Background = tone, VerticalAlignment = VerticalAlignment.Center },+ new TextBlock { Text = CableName(c), FontSize = 8.5, Foreground = TxtC, VerticalAlignment = VerticalAlignment.Center }, depBox));+ }+ });+ var note = new TextBlock { Text = "A cable breaks the normal at Gate / Filt in / VCA in / Ext in · loops run with a one-sample delay", FontSize = 7.5, Foreground = DimC, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };+ var botGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*") , ColumnSpacing = 12 };+ botGrid.Children.Add(new ScrollViewer { HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden, VerticalScrollBarVisibility = ScrollBarVisibility.Disabled, MaxWidth = 470, Content = bottomHost });+ botGrid.Children.Add(Col(Right(note), 1));+ var bottom = new Border { Height = 22, BorderBrush = Border2, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(10, 0), Child = botGrid };+ return new DockPanel { LastChildFill = true, Children = { Docked(top, Avalonia.Controls.Dock.Top), Docked(bottom, Avalonia.Controls.Dock.Bottom), new Border { Padding = new Thickness(6, 2), Child = field } } };+ }+ overlay.Child = OverlayBody();+ overlay.KeyDown += (_, e) => { if (e.Key == Key.Escape) { OpenOverlay(false); e.Handled = true; } };++ // ======================================================================+ // Status strip+ // ======================================================================+ string ModeName() => Poly() ? "True poly" : Sel("voicemode", 3) switch { 0 => "MONO", 1 => "DUO", _ => "PARA" };+ string FiltModeName() => Sel("filtmode", 3) switch { 0 => "HP/LP series", 1 => "LP/LP parallel stereo", _ => "HP/LP stereo" };+ string StatusText()+ {+ int busy = scN > 1 ? (int)scope[1] : 0;+ switch (vs.Centre)+ {+ case 1: return $"{FiltModeName()} · spacing {Space(G("spacing"))} · env amount {EnvAmt(G("fenvamt"))}{(On("basscomp") ? " · bass comp" : "")}";+ case 2:+ {+ string rate = On("lfosync") ? $"sync {LfoRate(G("lforate"))}" : LfoRate(G("lforate"));+ string dest = On("lfodest") ? "osc 2 + 4" : "all osc";+ return $"LFO {LfoNames[Sel("lfowave", 6)]} {rate} → {dest} · {(On("dlydigital") ? "digital delay" : "BBD")} {(On("dlyping") ? "ping-pong" : "stereo")}, mix {G("dlymix") * 100:0} %";+ }+ case 3:+ {+ int m = Sel("seqmode", 3);+ if (m == 0) return "Sequencer off · pick SEQ or ARP, then hold a key";+ var types = StepTypes(); int len = SeqLen();+ int rat = types.Take(len).Count(t => t == 1), ties = types.Take(len).Count(t => t == 2);+ string swing = $"swing {50 + G("seqswing") * 25:0} %";+ return m == 1+ ? $"{len} steps · {rat} ratchet{(rat == 1 ? "" : "s")} ×{Ratchet()} · {ties} tie{(ties == 1 ? "" : "s")} · {swing} · transposed from the keyboard"+ : $"Arp {new[] { "up", "down", "random" }[Sel("seqorder", 3)]} over {1 + Sel("arpoct", 3)} oct · {SeqRates[Sel("seqrate", 6)]} · {swing}{(On("seqlatch") ? " · latched" : "")}";+ }+ case 4:+ {+ var broken = CableList().Where(c => ConsortJacks.Normalled.Contains(c.Dst)).Select(c => ConsortJacks.Dst(c.Dst).Name).Distinct().ToList();+ string nb = broken.Count == 0 ? "all normals intact" : "normals broken at " + string.Join(" and ", broken);+ return (vs.PatchView == 0 ? "Matrix view · drag a cell for depth, Alt-click to remove · " : $"Jack strip · {ConsortJacks.Points} points · ") + nb;+ }+ default:+ {+ var sync = new List<string>();+ if (On("o2sync")) sync.Add("osc 2 sync → 1"); if (On("o4sync")) sync.Add("osc 4 sync → 3");+ return $"{ModeName()} · {busy} {(Poly() ? "voice" : "note")}{(busy == 1 ? "" : "s")}{(sync.Count > 0 ? " · " + string.Join(", ", sync) : "")} · drift {G("drift") * 100:0} %";+ }+ }+ }+ var statusLeft = new TextBlock { FontSize = 8, Foreground = Txt2, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };+ var statusRight = MonoText("", 8, Txt2);+ common.Add(() =>+ {+ statusLeft.Text = StatusText();+ if (scN > 8)+ {+ string rate = $"{scope[6] / 1000:0.#} kHz";+ statusRight.Text = vs.Centre == 3 ? $"{rate} · sync to host {scope[8]:0} BPM · CPU {scope[4] * 100:0.0} %"+ : $"{rate} · ×{(int)scope[5]} OS · 0 smp · CPU {scope[4] * 100:0.0} %";+ }+ });+ var statusGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 8 };+ statusGrid.Children.Add(statusLeft); statusGrid.Children.Add(Col(statusRight, 1));+ var status = new Border { Height = 18, Background = Inset, BorderBrush = Border2, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(8, 0), Child = statusGrid };+ DockPanel.SetDock(status, Avalonia.Controls.Dock.Bottom);++ // ---- assemble ---------------------------------------------------------------+ var bodyRow = new DockPanel { LastChildFill = true, Margin = new Thickness(5, 5, 5, 4), Children = { wheels, right, centreBox } };+ var main = new DockPanel { LastChildFill = true, Background = RailBg, Children = { status, strip, bodyRow } };+ var root = new Panel { Children = { main, overlay } };++ refreshAll = () =>+ {+ cableCache = null; // automation / presets may have moved the cables+ scN = engine.InstrumentScope(track, scope);+ foreach (var a in common) a();+ foreach (var a in tabReadouts[Math.Clamp(vs.Centre, 0, 4)]) a();+ foreach (var a in rightReadouts[Math.Clamp(vs.Right, 0, 1)]) a();+ if (vs.Overlay) foreach (var a in overlayReadouts) a();+ };+ ctx.SetInstLiveViz(Refresh);+ if (vs.Overlay) OpenOverlay(true);+ Refresh();+ return root;++ // local: a tab frame (bar + swapping body), optional extras on the right of the bar.+ (Control, Action<int>) TabFrame(string[] tabs, ContentControl host, Func<int, Control> body, bool centered, int initial, Action<int>? changed, Control? extrasCtl)+ {+ int sel = Math.Clamp(initial, 0, tabs.Length - 1); var btns = new Border[tabs.Length];+ void Hi()+ {+ for (int i = 0; i < tabs.Length; i++)+ {+ bool on = i == sel;+ btns[i].Background = on ? TabBg : Brushes.Transparent; btns[i].BorderBrush = on ? Amber : Brushes.Transparent;+ var tb = (TextBlock)btns[i].Child!; tb.Foreground = on ? AmberLit : MutedC; tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;+ }+ }+ void Select(int i) { sel = i; Hi(); host.Content = body(i); changed?.Invoke(i); }+ var bar = centered ? (Avalonia.Controls.Panel)new UniformGrid { Rows = 1 } : new StackPanel { Orientation = Orientation.Horizontal };+ for (int i = 0; i < tabs.Length; i++)+ {+ int iv = i;+ var b = new Border { Padding = new Thickness(8, 0), BorderThickness = new Thickness(0, 0, 0, 2), BorderBrush = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand),+ Child = new TextBlock { Text = tabs[i], FontSize = 9, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center } };+ b.PointerPressed += (_, _) => Select(iv);+ btns[i] = b; bar.Children.Add(b);+ }+ var barDock = new DockPanel { Height = 20, LastChildFill = centered };+ if (extrasCtl != null) { var ex = new Border { Padding = new Thickness(0, 0, 7, 0), Child = extrasCtl }; DockPanel.SetDock(ex, Avalonia.Controls.Dock.Right); barDock.Children.Add(ex); }+ if (!centered) DockPanel.SetDock(bar, Avalonia.Controls.Dock.Left);+ barDock.Children.Add(bar);+ var barBorder = new Border { BorderBrush = Border2, BorderThickness = new Thickness(0, 0, 0, 1), Child = barDock };+ DockPanel.SetDock(barBorder, Avalonia.Controls.Dock.Top);+ Select(sel);+ return (new DockPanel { LastChildFill = true, Children = { barBorder, host } }, Select);+ }+ }+}diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.csindex 4b268205..563bbbf6 100644--- a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs@@ -504,7 +504,7 @@ internal sealed class RackCardView(DeviceCardContext ctx)var f = new MenuFlyout();void Add(string h, int k) { var mi = new MenuItem { Header = h }; mi.Click += (_, _) => { int c = a.AddChain(k); if (c >= 0) Sel = c; _ctx.RequestRebuild(); }; f.Items.Add(mi); }Add("Nota Synth", 0); Add("Nota Sampler", 1); Add("Nota Physical", 2); Add("Nota Aurora", 5);- Add("Nota Volt", 6); Add("Nota Bass", 7); Add("Nota Pendulum", 8); Add("Nota Operator", 9); Add("Nota Grain", 10); Add("Nota Flux", 11); Add("Nota Monolith", 13); Add("Nota Pentad", 14);+ Add("Nota Volt", 6); Add("Nota Bass", 7); Add("Nota Pendulum", 8); Add("Nota Operator", 9); Add("Nota Grain", 10); Add("Nota Flux", 11); Add("Nota Monolith", 13); Add("Nota Pentad", 14); Add("Nota Consort", 15);f.ShowAt(anchor, showAtPointer: true);}@@ -1741,7 +1741,9 @@ internal sealed class RackCardView(DeviceCardContext ctx)mo.Click += (_, _) => { a.AddChain(13); _ctx.RequestRebuild(); };var pd = new MenuItem { Header = "Nota Pentad" };pd.Click += (_, _) => { a.AddChain(14); _ctx.RequestRebuild(); };- f.Items.Add(s); f.Items.Add(p); f.Items.Add(w); f.Items.Add(vo); f.Items.Add(ba); f.Items.Add(pe); f.Items.Add(op); f.Items.Add(gr); f.Items.Add(fl); f.Items.Add(mo); f.Items.Add(pd);+ var co = new MenuItem { Header = "Nota Consort" };+ co.Click += (_, _) => { a.AddChain(15); _ctx.RequestRebuild(); };+ f.Items.Add(s); f.Items.Add(p); f.Items.Add(w); f.Items.Add(vo); f.Items.Add(ba); f.Items.Add(pe); f.Items.Add(op); f.Items.Add(gr); f.Items.Add(fl); f.Items.Add(mo); f.Items.Add(pd); f.Items.Add(co);f.ShowAt(b, showAtPointer: true);};return b;@@ -1908,6 +1910,7 @@ internal sealed class RackCardView(DeviceCardContext ctx)Add("Nota Flux", 11);Add("Nota Monolith", 13);Add("Nota Pentad", 14);+ Add("Nota Consort", 15);f.ShowAt(anchor, showAtPointer: true);}diff --git a/src/managed/Nota.App/DeviceChainView.Shell.cs b/src/managed/Nota.App/DeviceChainView.Shell.csindex adb413ed..f948bca5 100644--- a/src/managed/Nota.App/DeviceChainView.Shell.cs+++ b/src/managed/Nota.App/DeviceChainView.Shell.cs@@ -90,6 +90,7 @@ public sealed partial class DeviceChainViewif (s.IsInstrument && _engine.InstrumentVoiceCount(_trackId) >= 0){var vt = Mono("0/16", 30); vt.Foreground = Teal; vt.TextAlignment = TextAlignment.Left;+ if (s.VoiceLabel != null) { vt.Width = double.NaN; vt.MinWidth = 30; } // e.g. "PARA 3/4" — size to the text_deviceLiveRefreshers.Add(() => { int v = _engine.InstrumentVoiceCount(_trackId); vt.Text = s.VoiceLabel?.Invoke(_engine, _trackId, v) ?? (_engine.PluginParamGet(_trackId, -1, IndexOfId("mono")) > 0.5f ? "MONO" : $"{Math.Max(0, v)}/16"); });right.Children.Add(vt);}diff --git a/src/managed/Nota.App/MainWindow.Browser.cs b/src/managed/Nota.App/MainWindow.Browser.csindex e917029d..0256ed08 100644--- a/src/managed/Nota.App/MainWindow.Browser.cs+++ b/src/managed/Nota.App/MainWindow.Browser.cs@@ -59,6 +59,7 @@ public partial class MainWindow12 => Engine.AddRhythmTrack(),13 => Engine.AddMonolithTrack(),14 => Engine.AddPentadTrack(),+ 15 => Engine.AddConsortTrack(),1 => Engine.AddSamplerInstrumentTrack(),_ => Engine.AddInstrumentTrack(),};diff --git a/src/managed/Nota.App/MainWindow.Dnd.cs b/src/managed/Nota.App/MainWindow.Dnd.csindex 39bc94df..dfe3c803 100644--- a/src/managed/Nota.App/MainWindow.Dnd.cs+++ b/src/managed/Nota.App/MainWindow.Dnd.cs@@ -63,6 +63,7 @@ public partial class MainWindow12 => Engine.AddRhythmTrack(),13 => Engine.AddMonolithTrack(),14 => Engine.AddPentadTrack(),+ 15 => Engine.AddConsortTrack(),1 => Engine.AddSamplerInstrumentTrack(),_ => Engine.AddInstrumentTrack(),};diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.csindex 33e027fa..b25bbc22 100644--- a/src/managed/Nota.App/PreferencesWindow.cs+++ b/src/managed/Nota.App/PreferencesWindow.cs@@ -546,7 +546,7 @@ public sealed class PreferencesWindow : NotaWindow("⌘A", "Toggle automation mode"),("⌘M", "Toggle the Mixer view"),("Tab", "Switch Devices / Clip in the detail panel"),- ("Esc", "Cancel the current gesture / clear the selection"),+ ("Esc", "Cancel the current gesture / clear the selection · close the patch-bay overlay"),("⌘G ⌘⇧G", "Group / ungroup selected tracks"),("⌘C ⌘X ⌘V", "Copy / cut / paste clip (or automation range)"),("⌘D", "Duplicate the selected clip(s) / range"),@@ -578,6 +578,7 @@ public sealed class PreferencesWindow : NotaWindow("Drag ⠿", "Reorder devices (◀ ▶)"),("Drag knob", "Change a device value · hold ⌘ or ⇧ for fine steps"),("Double-click knob", "Reset the value to its default"),+ ("Drag jack → jack", "Patch a cable in Nota Consort · ⌥-click a jack to pull its cables"),}),};diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex 9785e591..136b40f9 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -264,6 +264,8 @@ public interface IAudioEngine : IDisposableint AddMonolithTrack();/// <summary>Adds an instrument track with the built-in Nota Pentad 5-voice poly synth (kind 14).</summary>int AddPentadTrack();+ /// <summary>Adds an instrument track with the built-in Nota Consort paraphonic semi-modular synth (kind 15).</summary>+ int AddConsortTrack();/// <summary>UI editing channel for the track's instrument (e.g. Rhythm step patterns).</summary>void InstrumentAction(int trackId, int id, int iarg, float farg);/// <summary>Loads a sample file into a Nota Grain track (kind 10). True on success.</summary>diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.csindex 85dafeee..61323d1e 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs@@ -307,6 +307,9 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_engine_add_pentad_track")]internal static partial int AddPentadTrack(IntPtr engine);+ [LibraryImport(Lib, EntryPoint = "nota_engine_add_consort_track")]+ internal static partial int AddConsortTrack(IntPtr engine);+[LibraryImport(Lib, EntryPoint = "nota_track_instrument_action")]internal static partial void InstrumentAction(IntPtr engine, int trackId, int id, int iarg, float farg);diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.csindex 4c5e5c25..2a4888d0 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs@@ -627,6 +627,15 @@ public sealed partial class NotaEnginereturn id;}+ /// <summary>Adds an instrument track with the built-in Nota Consort paraphonic synth. Returns its id.</summary>+ public int AddConsortTrack()+ {+ ThrowIfDisposed();+ var id = NativeMethods.AddConsortTrack(_handle);+ if (id <= 0) throw new NotaEngineException("Failed to add Consort track.");+ return id;+ }+/// <summary>UI editing channel for the track's instrument (e.g. Nota Rhythm step patterns).</summary>public void InstrumentAction(int trackId, int id, int iarg, float farg){ ThrowIfDisposed(); NativeMethods.InstrumentAction(_handle, trackId, id, iarg, farg); }diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.csindex 47c8b619..92f93a50 100644--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs@@ -261,6 +261,95 @@ public sealed class FactoryPresetCatalog : IFactoryPresetsInst("pentad", 14, "Random Computer", ("oasaw", 0f), ("oapulse", 1f), ("lfotri", 0f), ("lfosaw", 1f), ("lfosquare", 1f), ("lforate", 0.75f), ("lfoamt", 0.8f), ("wmfilter", 1f), ("cutoff", 0.6f), ("reso", 0.5f));Inst("pentad", 14, "Dive Bomb", ("oasync", 1f), ("pmenv", 1f), ("pmfreqa", 1f), ("mixb", 0f), ("fattack", 0.8f), ("fdecay", 0.85f), ("fsustain", 0f), ("cutoff", 0.6f), ("reso", 0.3f), ("glide", 0.8f), ("glidemode", 0.5f));+ // ---- Nota Consort (kind 15) — paraphonic semi-modular. Octave 32'/16'/8'/4'/2' =+ // 0/.25/.5/.75/1; freq .5 = 0 (±7 st); wave tri/saw/square/pulse = 0/.333/.667/1;+ // voice mode Mono/Duo/Para = 0/.5/1 (+ truepoly); filter HP/LP ser, LP/LP st, HP/LP st+ // = 0/.5/1; cutoff v = log10(Hz/20)/3; spacing .5 + oct/6; env amount .5 + d/20.+ // ConsortSeq(types, pitches) writes the 16 steps ('n' note, 'r' ratchet, 't' tie,+ // '.' rest); Cab(slot, source, dest, depth) patches a cable (jack indices, Consort.h).+ // Paraphonic+ Inst("consort", 15, "Stereo Consort", Cat(P(("o2freq", 0.505f), ("o3oct", 0.25f), ("o3wave", 0.667f), ("o4oct", 0.75f), ("o4wave", 1f), ("pw", 0.42f),+ ("mix1", 0.88f), ("mix2", 0.74f), ("mix3", 0.64f), ("mix4", 0.5f), ("filtmode", 0.5f), ("cutoff", 0.497f), ("reso", 0.35f), ("spacing", 0.667f), ("fenvamt", 0.72f),+ ("fattack", 0.25f), ("fdecay", 0.6f), ("fsustain", 0.46f), ("frelease", 0.6f), ("aattack", 0.3f), ("adecay", 0.68f), ("asustain", 0.72f), ("arelease", 0.66f),+ ("drift", 0.34f), ("glide", 0.519f), ("glidetype", 1f), ("lfopitch", 0.546f), ("lforate", 0.6f), ("lfodest", 1f),+ ("dlymix", 0.3f), ("dlyfb", 0.5f), ("dlytime", 0.678f), ("dlyspacing", 0.63f), ("dlyping", 1f))));+ Inst("consort", 15, "Para Strings", ("o2freq", 0.507f), ("o3freq", 0.493f), ("o4freq", 0.511f), ("filtmode", 0.5f), ("cutoff", 0.56f), ("reso", 0.1f), ("spacing", 0.583f),+ ("fenvamt", 0.62f), ("fattack", 0.7f), ("fdecay", 0.75f), ("fsustain", 0.6f), ("frelease", 0.75f), ("aattack", 0.72f), ("adecay", 0.7f), ("asustain", 0.9f), ("arelease", 0.78f),+ ("drift", 0.45f), ("lforate", 0.36f), ("lfopitch", 0.54f), ("dlymix", 0.22f), ("dlydigital", 1f), ("dlyping", 0f), ("dlytime", 0.72f), ("dlyfb", 0.35f));+ Inst("consort", 15, "Glass Chords", ("o1wave", 0f), ("o2wave", 1f), ("o2oct", 0.75f), ("o3wave", 0f), ("o4wave", 1f), ("pw", 0.6f), ("filtmode", 1f), ("cutoff", 0.46f),+ ("spacing", 0.833f), ("reso", 0.25f), ("fenvamt", 0.75f), ("fattack", 0f), ("fdecay", 0.55f), ("fsustain", 0.2f), ("frelease", 0.6f),+ ("aattack", 0f), ("adecay", 0.7f), ("asustain", 0.3f), ("arelease", 0.7f), ("lfopwm", 0.3f), ("lforate", 0.45f), ("dlymix", 0.35f), ("dlyfb", 0.45f), ("dlytime", 0.585f));+ Inst("consort", 15, "Consort Brass", ("o2freq", 0.509f), ("o3freq", 0.491f), ("o4freq", 0.505f), ("cutoff", 0.42f), ("reso", 0.15f), ("fenvamt", 0.78f),+ ("fattack", 0.55f), ("fdecay", 0.6f), ("fsustain", 0.5f), ("frelease", 0.5f), ("aattack", 0.45f), ("asustain", 0.9f), ("arelease", 0.5f),+ ("mixdrive", 1f), ("spacing", 0.55f), ("drift", 0.3f));+ Inst("consort", 15, "Spread Voicing", ("o1oct", 0.25f), ("o4oct", 0.75f), ("o3wave", 0.667f), ("cutoff", 0.6f), ("fenvamt", 0.62f), ("fdecay", 0.62f), ("fsustain", 0.45f),+ ("aattack", 0.2f), ("adecay", 0.7f), ("asustain", 0.8f), ("arelease", 0.62f), ("dlymix", 0.25f), ("drift", 0.3f));+ Inst("consort", 15, "Duo Fifths", ("voicemode", 0.5f), ("o2freq", 1f), ("o4freq", 1f), ("cutoff", 0.62f), ("reso", 0.3f), ("fenvamt", 0.68f), ("fdecay", 0.55f), ("fsustain", 0.45f),+ ("glide", 0.434f), ("glidetype", 1f), ("dlymix", 0.28f), ("dlytime", 0.627f));+ Inst("consort", 15, "Duo Sync Pad", Cat(P(("voicemode", 0.5f), ("o2sync", 1f), ("o2freq", 0.893f), ("o4freq", 0.505f), ("mix1", 0.5f), ("mix2", 0.85f), ("mix3", 0.7f), ("mix4", 0.6f),+ ("cutoff", 0.58f), ("reso", 0.2f), ("fenvamt", 0.6f), ("aattack", 0.62f), ("asustain", 0.9f), ("arelease", 0.72f), ("lfowave", 0f), ("lforate", 0.25f), ("dlymix", 0.3f)),+ Cab(1, 1, 6, 0.3f)));+ // True poly+ Inst("consort", 15, "Poly Pad", ("truepoly", 1f), ("o2freq", 0.507f), ("o3oct", 0.25f), ("o3wave", 0.667f), ("o4oct", 0.75f), ("o4wave", 0f), ("mix3", 0.55f), ("mix4", 0.45f),+ ("cutoff", 0.5f), ("fenvamt", 0.64f), ("fattack", 0.6f), ("fdecay", 0.7f), ("fsustain", 0.55f), ("frelease", 0.7f), ("aattack", 0.7f), ("asustain", 0.9f), ("arelease", 0.8f),+ ("lfocut", 0.25f), ("lforate", 0.3f), ("drift", 0.4f), ("dlymix", 0.2f));+ Inst("consort", 15, "Poly Keys", ("truepoly", 1f), ("o1wave", 1f), ("o3wave", 1f), ("o3oct", 0.25f), ("mix3", 0.5f), ("mix4", 0.4f), ("pw", 0.5f), ("cutoff", 0.55f), ("fenvamt", 0.75f),+ ("fdecay", 0.55f), ("fsustain", 0.25f), ("aattack", 0.1f), ("adecay", 0.65f), ("asustain", 0.5f), ("arelease", 0.55f), ("velvca", 1f), ("dlymix", 0.25f));+ // Mono+ Inst("consort", 15, "Ladder Bass", ("voicemode", 0f), ("unison", 0f), ("o1oct", 0.25f), ("o2oct", 0.25f), ("o2freq", 0.507f), ("o3oct", 0f), ("o3wave", 0.667f), ("mix1", 0.9f), ("mix2", 0.8f),+ ("mix3", 0.6f), ("mix4", 0f), ("cutoff", 0.36f), ("reso", 0.3f), ("fenvamt", 0.72f), ("fdecay", 0.5f), ("fsustain", 0.2f), ("frelease", 0.4f),+ ("adecay", 0.55f), ("asustain", 0.8f), ("arelease", 0.35f), ("mixdrive", 1f), ("spacing", 0.5f));+ Inst("consort", 15, "Deep Sub", ("voicemode", 0f), ("unison", 0f), ("o1oct", 0.25f), ("o1wave", 0f), ("o2oct", 0f), ("o2wave", 0.667f), ("mix1", 0.9f), ("mix2", 0.6f), ("mix3", 0f), ("mix4", 0f),+ ("cutoff", 0.3f), ("reso", 0.1f), ("fenvamt", 0.6f), ("fdecay", 0.45f), ("fsustain", 0.3f), ("basscomp", 1f), ("spacing", 0.5f), ("arelease", 0.3f));+ Inst("consort", 15, "Unison Lead", ("voicemode", 0f), ("unison", 1f), ("drift", 0.45f), ("o4oct", 0.75f), ("cutoff", 0.62f), ("reso", 0.35f), ("fenvamt", 0.65f), ("fdecay", 0.55f),+ ("fsustain", 0.5f), ("glide", 0.36f), ("glidetype", 0.5f), ("glidegated", 1f), ("lfopitch", 0.565f), ("lforate", 0.64f), ("dlymix", 0.3f), ("dlytime", 0.627f));+ Inst("consort", 15, "Sync Lead", Cat(P(("voicemode", 0f), ("unison", 0f), ("o2sync", 1f), ("o2freq", 0.857f), ("mix1", 0.4f), ("mix2", 0.9f), ("mix3", 0f), ("mix4", 0f),+ ("cutoff", 0.7f), ("fenvamt", 0.62f), ("fdecay", 0.55f), ("fsustain", 0.25f), ("glide", 0.3f), ("dlymix", 0.25f)),+ Cab(1, 2, 6, 0.35f)));+ Inst("consort", 15, "Feedback Growl", ("voicemode", 0f), ("unison", 0f), ("o1oct", 0.25f), ("o2oct", 0.25f), ("o2freq", 0.505f), ("mix3", 0f), ("mix4", 0f), ("mixext", 0.6f),+ ("mixdrive", 1f), ("cutoff", 0.42f), ("reso", 0.45f), ("fenvamt", 0.7f), ("fdecay", 0.45f), ("fsustain", 0.35f), ("spacing", 0.55f));+ Inst("consort", 15, "Ladder Whistle", ("voicemode", 0f), ("unison", 0f), ("mix1", 0f), ("mix2", 0f), ("mix3", 0f), ("mix4", 0f), ("mixnoise", 0.02f), ("reso", 1f), ("kbdtrk", 1f),+ ("cutoff", 0.55f), ("fenvamt", 0.5f), ("spacing", 0.667f), ("glide", 0.36f), ("lfocut", 0.12f), ("lforate", 0.7f), ("aattack", 0.3f), ("arelease", 0.5f));+ Inst("consort", 15, "Wheel Wah", Cat(P(("voicemode", 0f), ("cutoff", 0.35f), ("reso", 0.6f), ("fenvamt", 0.55f), ("glide", 0.3f), ("modwheel", 0.4f)),+ Cab(1, 17, 10, 0.8f), Cab(2, 17, 11, 0.6f), Cab(3, 16, 4, 0.1f)));+ // Sequencer / arpeggiator+ Inst("consort", 15, "Ratchet Run", Cat(P(("seqmode", 0.5f), ("seqrate", 0.6f), ("seqswing", 0.24f), ("cutoff", 0.5f), ("reso", 0.4f), ("fenvamt", 0.72f), ("fdecay", 0.45f),+ ("fsustain", 0.15f), ("adecay", 0.5f), ("asustain", 0.3f), ("arelease", 0.35f), ("dlymix", 0.3f), ("dlyfb", 0.45f)),+ ConsortSeq("n.nrnt.nn.rnnt.n", 0, 0, 5, -2, 7, 7, 0, 10, 12, 0, -2, 5, 7, 7, 0, 3)));+ Inst("consort", 15, "Acid Run", Cat(P(("voicemode", 0f), ("unison", 0f), ("seqmode", 0.5f), ("seqrate", 0.6f), ("seqswing", 0.2f), ("o1oct", 0.25f), ("mix1", 0.9f), ("mix2", 0f),+ ("mix3", 0f), ("mix4", 0f), ("cutoff", 0.38f), ("reso", 0.82f), ("fenvamt", 0.82f), ("fdecay", 0.45f), ("fsustain", 0.05f), ("adecay", 0.5f), ("asustain", 0.6f),+ ("glide", 0.3f), ("glidetype", 0.5f), ("glidegated", 1f), ("mixdrive", 1f), ("spacing", 0.5f), ("dlymix", 0.2f)),+ ConsortSeq("nntnrn.nntn.nrtn", 0, 0, 0, 12, 0, 3, 0, -2, 0, 0, 10, 0, 7, 12, 12, 0)));+ Inst("consort", 15, "Arp Cascade", ("seqmode", 1f), ("arpoct", 0.5f), ("seqrate", 0.6f), ("o1wave", 0f), ("o3wave", 0f), ("cutoff", 0.6f), ("fenvamt", 0.7f), ("fdecay", 0.42f),+ ("fsustain", 0.1f), ("adecay", 0.45f), ("asustain", 0.2f), ("arelease", 0.45f), ("dlymix", 0.38f), ("dlyfb", 0.55f), ("dlyping", 1f));+ Inst("consort", 15, "Random Arp", ("seqmode", 1f), ("seqorder", 1f), ("arpoct", 1f), ("seqrate", 0.8f), ("lfowave", 0.8f), ("lfosync", 1f), ("lforate", 0.846f), ("lfocut", 0.45f),+ ("cutoff", 0.5f), ("reso", 0.35f), ("fdecay", 0.4f), ("fsustain", 0.1f), ("adecay", 0.42f), ("asustain", 0.15f), ("dlymix", 0.35f), ("dlydigital", 1f));+ Inst("consort", 15, "Latch Sequence", Cat(P(("seqmode", 0.5f), ("seqlatch", 1f), ("seqrate", 0.2f), ("seqlen", 0.733f), ("cutoff", 0.52f), ("fenvamt", 0.62f), ("fattack", 0.3f),+ ("fdecay", 0.6f), ("aattack", 0.3f), ("adecay", 0.65f), ("asustain", 0.5f), ("arelease", 0.6f), ("dlymix", 0.3f), ("drift", 0.4f)),+ ConsortSeq("ntn.nrntn.nt....", 0, 0, 7, 0, 3, 5, 10, 10, 12, 0, 7, 7, 0, 0, 0, 0)));+ // Modular (patch bay)+ Inst("consort", 15, "Patched Drift", Cat(P(("lfowave", 1f), ("lforate", 0.36f), ("drift", 0.6f), ("cutoff", 0.52f), ("fenvamt", 0.62f), ("aattack", 0.4f), ("adecay", 0.7f),+ ("asustain", 0.8f), ("arelease", 0.7f), ("dlymix", 0.35f), ("dlyfb", 0.5f)),+ Cab(1, 1, 7, 0.14f), Cab(2, 2, 16, 0.38f), Cab(3, 6, 14, 0.48f)));+ Inst("consort", 15, "Ring Bells", Cat(P(("truepoly", 1f), ("o1wave", 0f), ("o3wave", 0f), ("o3oct", 0.75f), ("o3freq", 0.736f), ("mix1", 0.9f), ("mix2", 0f), ("mix3", 0f), ("mix4", 0f),+ ("cutoff", 0.8f), ("fenvamt", 0.5f), ("adecay", 0.7f), ("asustain", 0f), ("arelease", 0.7f), ("dlymix", 0.3f)),+ Cab(1, 6, 14, 0.95f)));+ Inst("consort", 15, "FM Growl", Cat(P(("voicemode", 0f), ("unison", 0f), ("o1oct", 0.25f), ("o4oct", 0.25f), ("mix2", 0f), ("mix3", 0f), ("mix4", 0f), ("cutoff", 0.45f), ("reso", 0.3f),+ ("fenvamt", 0.7f), ("fdecay", 0.5f), ("fsustain", 0.3f), ("mixdrive", 1f)),+ Cab(1, 7, 5, 0.28f)));+ Inst("consort", 15, "Trance Gate", Cat(P(("lfowave", 0.6f), ("lfosync", 1f), ("lforate", 0.846f), ("cutoff", 0.55f), ("fenvamt", 0.6f), ("aattack", 0.2f), ("adecay", 0.45f),+ ("asustain", 0.6f), ("arelease", 0.3f), ("dlymix", 0.3f)),+ Cab(1, 1, 3, 1f)));+ Inst("consort", 15, "Wind Noise", Cat(P(("reso", 0.85f), ("kbdtrk", 1f), ("lfowave", 1f), ("lforate", 0.3f), ("lfocut", 0.55f), ("aattack", 0.6f), ("arelease", 0.75f),+ ("cutoff", 0.5f), ("fenvamt", 0.5f), ("spacing", 0.667f), ("dlymix", 0.3f)),+ Cab(1, 8, 13, 1f)));+ Inst("consort", 15, "Touch Stereo", Cat(P(("truepoly", 1f), ("velvca", 1f), ("spacing", 0.5f), ("cutoff", 0.35f), ("fenvamt", 0.6f), ("fdecay", 0.5f), ("fsustain", 0.2f),+ ("adecay", 0.6f), ("asustain", 0.4f), ("arelease", 0.5f)),+ Cab(1, 13, 11, 1f), Cab(2, 15, 10, 0.7f)));+ Inst("consort", 15, "Delay Warp", Cat(P(("lfowave", 0f), ("lforate", 0.28f), ("dlymix", 0.5f), ("dlyfb", 0.7f), ("dlytime", 0.72f), ("cutoff", 0.58f), ("fenvamt", 0.7f),+ ("fdecay", 0.5f), ("fsustain", 0.15f), ("adecay", 0.55f), ("asustain", 0.3f)),+ Cab(1, 1, 16, 0.4f)));+// ---- EQ-8 (kind 0) — 8 bands × (On/Type/Freq/Gain/Q), param names "<band> <field>",// band 1 = low shelf, 2/3 = bells, 4 = high shelf (defaults). Type: 0 LowCut,// 1 LowShelf, 2 Bell, 3 Notch, 4 HighShelf, 5 HighCut.@@ -581,6 +670,28 @@ public sealed class FactoryPresetCatalog : IFactoryPresets? PresetService.ApplyInPlace(doc, engine, trackId, deviceIndex): "Unknown factory preset.";+ // Nota Consort preset helpers (see the Consort block above).+ private static (string, float)[] P(params (string, float)[] ps) => ps;+ private static (string, float)[] Cat(params (string, float)[][] parts)+ {+ var l = new List<(string, float)>();+ foreach (var p in parts) l.AddRange(p);+ return l.ToArray();+ }+ private static (string, float)[] ConsortSeq(string types, params int[] pitches)+ {+ var l = new List<(string, float)>();+ for (int s = 0; s < 16; s++)+ {+ char c = s < types.Length ? types[s] : 'n';+ l.Add(($"st{s + 1}", c switch { 'r' => 1f / 3f, 't' => 2f / 3f, '.' => 1f, _ => 0f }));+ l.Add(($"sp{s + 1}", 0.5f + (s < pitches.Length ? pitches[s] : 0) / 48f));+ }+ return l.ToArray();+ }+ private static (string, float)[] Cab(int slot, int src, int dst, float depth)+ => new[] { ($"c{slot}src", src / 63f), ($"c{slot}dst", dst / 63f), ($"c{slot}amt", 0.5f + depth / 2f) };+private void Inst(string group, int kind, string name, params (string Id, float Value)[] ps)=> Add(group, name, "builtin-instrument", kind, isInstrument: true, isMidi: false, ps);diff --git a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs b/src/managed/Nota.Infrastructure/Persistence/PresetService.csindex 25042124..f7381745 100644--- a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs+++ b/src/managed/Nota.Infrastructure/Persistence/PresetService.cs@@ -172,6 +172,7 @@ public static class PresetService12 => engine.AddRhythmTrack(),13 => engine.AddMonolithTrack(),14 => engine.AddPentadTrack(),+ 15 => engine.AddConsortTrack(),_ => engine.AddInstrumentTrack(),};if (t <= 0) return "Failed to add instrument.";diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.csindex e3715a5d..444a1e37 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs@@ -540,6 +540,7 @@ public sealed class ProjectService{ Kind: 12 } => engine.AddRhythmTrack(), // Nota Rhythm{ Kind: 13 } => engine.AddMonolithTrack(), // Nota Monolith{ Kind: 14 } => engine.AddPentadTrack(), // Nota Pentad+ { Kind: 15 } => engine.AddConsortTrack(), // Nota Consort_ => engine.AddInstrumentTrack(), // Nota Synth};if (t.Instrument?.State is { } synthState)diff --git a/src/managed/Nota.Mcp/Tools/InstrumentTools.cs b/src/managed/Nota.Mcp/Tools/InstrumentTools.csindex 182f5133..723e6443 100644--- a/src/managed/Nota.Mcp/Tools/InstrumentTools.cs+++ b/src/managed/Nota.Mcp/Tools/InstrumentTools.cs@@ -19,7 +19,7 @@ public sealed class InstrumentTools(IAudioEngine engine, IEngineDispatch dispatc(0, "Nota Synth"), (1, "Nota Sampler"), (2, "Nota Physical"), (3, "Instrument Rack"),(4, "Drum Rack"), (5, "Nota Aurora"), (6, "Nota Volt"), (7, "Nota Bass"),(8, "Nota Pendulum"), (9, "Nota Operator"), (10, "Nota Grain"), (11, "Nota Flux"),- (12, "Nota Rhythm"), (13, "Nota Monolith"), (14, "Nota Pentad"),+ (12, "Nota Rhythm"), (13, "Nota Monolith"), (14, "Nota Pentad"), (15, "Nota Consort"),};public sealed record InstrumentKind(int Kind, string Name);@@ -29,7 +29,7 @@ public sealed class InstrumentTools(IAudioEngine engine, IEngineDispatch dispatcpublic InstrumentKind[] ListInstrumentKinds() => Array.ConvertAll(Kinds, k => new InstrumentKind(k.Kind, k.Name));[McpServerTool(Name = "add_instrument_track"), Description("Add an instrument track with the given built-in kind (see list_instrument_kinds). Returns the track id.")]- public Task<int> AddInstrumentTrack([Description("Instrument kind id (0..14)")] int kind) => Mutate(() => kind switch+ public Task<int> AddInstrumentTrack([Description("Instrument kind id (0..15)")] int kind) => Mutate(() => kind switch{1 => E.AddSamplerInstrumentTrack(),2 => E.AddPhysicalSynthTrack(),@@ -45,6 +45,7 @@ public sealed class InstrumentTools(IAudioEngine engine, IEngineDispatch dispatc12 => E.AddRhythmTrack(),13 => E.AddMonolithTrack(),14 => E.AddPentadTrack(),+ 15 => E.AddConsortTrack(),_ => E.AddInstrumentTrack(), // 0 = Nota Synth});diff --git a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.csindex a74e64cc..129f27b6 100644--- a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs+++ b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs@@ -190,6 +190,7 @@ public sealed partial class BrowserViewModel : ObservableObjectnew() { Name = "Nota Rhythm", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 12, Sub = "drum machine" },new() { Name = "Nota Monolith", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 13, Sub = "mono synth" },new() { Name = "Nota Pentad", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 14, Sub = "poly synth" },+ new() { Name = "Nota Consort", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 15, Sub = "paraphonic synth" },new() { Name = "Nota Sampler", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 1, Sub = "built-in" },new() { Name = "Nota Instrument Rack", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 3, Sub = "built-in" },new() { Name = "Nota Drum Rack", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 4, Sub = "built-in" }diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex f59b5bec..17295af3 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -388,6 +388,8 @@ NOTA_API int32_t nota_engine_add_rhythm_track(NotaEngine* engine);NOTA_API int32_t nota_engine_add_monolith_track(NotaEngine* engine);/* Adds an instrument track with the built-in Nota Pentad (5-voice Prophet-5-style poly, kind 14). id (>0). */NOTA_API int32_t nota_engine_add_pentad_track(NotaEngine* engine);+/* Adds an instrument track with the built-in Nota Consort (paraphonic semi-modular synth, kind 15). id (>0). */+NOTA_API int32_t nota_engine_add_consort_track(NotaEngine* engine);/* UI editing channel for the track's instrument (e.g. Nota Rhythm step patterns):* id/iarg/farg are instrument-specific (see the instrument's action()). */NOTA_API void nota_track_instrument_action(NotaEngine* engine, int32_t track_id, int32_t id, int32_t iarg, float farg);diff --git a/src/native/nota.engine/src/Consort.h b/src/native/nota.engine/src/Consort.hnew file mode 100644index 00000000..ba772211--- /dev/null+++ b/src/native/nota.engine/src/Consort.h@@ -0,0 +1,1456 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Consort — the built-in paraphonic semi-modular synth (kind 15), in the spirit of+// a four-oscillator paraphonic Moog (Matriarch-style architecture). Nota's own DSP.+//+// VCO 1 ─┐ (2 syncs to 1) ┌─ ladder A ─┐ (HP/LP series, LP/LP or+// VCO 2 ─┤ │ │ HP/LP parallel stereo,+// VCO 3 ─┼─→ Mixer (+ noise, EXT, drive) ─────────┤ ├─→ VCA ─→ Σ ─→ BBD delay ─→ out+// VCO 4 ─┘ (4 syncs to 3) └─ ladder B ─┘ (B = A + spacing)+// Env 1 → cutoff · Env 2 → VCA · LFO (6 shapes) → pitch / cutoff / PWM+//+// Voicing. MONO (all four oscillators on one note), DUO (1+2 and 3+4 each take a note) and+// PARA (every oscillator its own note) share ONE filter / VCA / envelope pair — true+// paraphony, with Multi-trig (retrigger the shared envelopes on every new note) and Unison+// (idle oscillators double held notes, detuned). "True poly" swaps that for 16 complete+// voices (four oscillators, two ladders, two envelopes each). Glide per oscillator: linear+// constant-rate, linear constant-time or exponential, optionally gated (legato only).+//+// Patch bay. Twelve cables, each a (source jack, destination jack, bipolar depth) triple of+// plugin-params — so a patch saves, clones, lives in presets and the depth automates.+// Sources are audio or CV (oscillators, filter out, noise, LFO, envelopes, keyboard, the+// sequencer's pitch / gate / clock, two attenuators and a summing node); destinations are+// pitch / PWM / cutoff / resonance / VCA CV / delay / LFO rate, the attenuator and sum+// inputs, and four NORMALLED inputs — Gate 1 / Gate 2 (the envelopes' keyboard gates), Filter+// in (the mixer), VCA in (the filter) and EXT in (the VCA output, the classic Moog feedback+// loop) — where inserting a cable breaks the normal. Every cable reads its source from the+// previous sample, so feedback loops are legal. Depth is squared (fine near zero, exact+// 1 V/oct at ±100 for keyboard / sequencer pitch into pitch or cutoff).+//+// Sequencer / arpeggiator: 16 steps (note / ratchet / tie / rest, ±24 st per step), 1/4..1/32+// with swing, forward / backward / random order, latch; transposed from the keyboard (SEQ) or+// walking the held chord over 1..3 octaves (ARP, the step types still shape the rhythm).+// Locked to the host grid while the transport rolls, free-running at the host tempo when not.+//+// Analog delay: a stereo bucket-brigade model — clock-dependent bandwidth (longer = darker),+// a 2:1 compander with its breathing, soft overload and hiss, a slewed clock so moving the+// time transposes the tail; Ping-pong or stereo, or a clean digital line.+//+// DSP quality: voices run at ×1/×2/×4 with HIIR decimation, oscillators use 4-point polyBLEP /+// polyBLAMP (Pentad's core), the ladders are zero-delay-feedback with per-sample linearised+// saturation (self-oscillating, key-trackable, HP taps by mode mixing). Deterministic state+// (seeded, re-seeded on play edges / jumps) so a freeze equals the live render.+//+// All parameters ride the Instrument plugin-param interface (normalized 0..1, stable ids).+// Header-only; allocation-free after construction (the delay line is calloc'd, so an+// untouched instance — e.g. the engine's default-value probe — costs no page faults).++#pragma once++#include "Instrument.h"+#include "Pentad.h" // pentad:: band-limited oscillator core + fast math, hiir decimators++#include <algorithm>+#include <atomic>+#include <chrono>+#include <climits>+#include <cmath>+#include <cstdint>+#include <cstdlib>+#include <cstring>+#include <memory>+#include <string>+#include <vector>++#if defined(__SSE2__) || defined(_M_X64) || (defined(_M_IX86_FP) && _M_IX86_FP >= 2)+#include <xmmintrin.h>+#define NOTA_CONSORT_FTZ_X86 1+#elif defined(__aarch64__) && !defined(_MSC_VER)+#define NOTA_CONSORT_FTZ_ARM 1+#endif++namespace nota {++namespace consort {++// Patch-bay jacks. The indices are persisted (a cable's source/dest param stores+// index / kJackScale) — APPEND ONLY. The editor mirrors these tables.+enum Src : int {+ SrcNone = 0, SrcLfo, SrcEnv1, SrcEnv2, SrcOsc1, SrcOsc2, SrcOsc3, SrcOsc4, SrcNoise, SrcFilt,+ SrcSeqPitch, SrcSeqGate, SrcClock, SrcKbdPitch, SrcKbdGate, SrcVelocity, SrcAftertouch, SrcModWheel,+ SrcAtten1, SrcAtten2, SrcSum,+ kSrcN+};+enum Dst : int {+ DstNone = 0, DstLfoRate, DstGate1, DstGate2, DstPitchAll, DstPitch1, DstPitch2, DstPitch3, DstPitch4, DstPwm,+ DstCut1, DstCut2, DstReso, DstFiltIn, DstVcaCv, DstVcaIn, DstDlyTime, DstDlyFb, DstDlyMix, DstExtIn,+ DstAtten1, DstAtten2, DstSum,+ kDstN+};+constexpr int kJackScale = 63; // room for future jacks without re-encoding saved patches++inline bool dstIsGlobal(int d) { return d == DstLfoRate || d == DstDlyTime || d == DstDlyFb || d == DstDlyMix; }+// Destination units per unit of source at depth ±100 %.+inline float dstScale(int d) {+ switch (d) {+ case DstLfoRate: return 4.0f; // octaves of rate+ case DstPitchAll: case DstPitch1: case DstPitch2: case DstPitch3: case DstPitch4: return 60.0f; // semitones+ case DstPwm: return 0.45f; // duty+ case DstCut1: case DstCut2: return 5.0f; // octaves (1 V/oct from kbd pitch)+ case DstDlyTime: return 2.0f; // octaves of time+ default: return 1.0f;+ }+}++inline float triVal(double ph) { return ph < 0.5 ? static_cast<float>(4.0 * ph - 1.0) : static_cast<float>(3.0 - 4.0 * ph); }++// Triangle slope corners (at phase 0.5 and at the wrap) as BLAMP residuals. p0 = phase before+// the span, the oscillator's phase is after it; the span ends tEnd samples before the current one.+inline void triCorners(pentad::Osc& o, double p0, float wrapD, float tEnd, double dt) {+ const float sl = static_cast<float>(8.0 * dt);+ const float inv = static_cast<float>(1.0 / dt);+ const float p1 = static_cast<float>(o.ph);+ if (wrapD >= 0.0f) {+ if (p0 < 0.5) o.ring.blamp(tEnd + (0.5f + p1) * inv, -sl);+ o.ring.blamp(wrapD, sl);+ if (p1 >= 0.5f) o.ring.blamp(tEnd + (p1 - 0.5f) * inv, -sl);+ } else if (p0 < 0.5 && p1 >= 0.5f) {+ o.ring.blamp(tEnd + (p1 - 0.5f) * inv, -sl);+ }+}++// One band-limited oscillator sample. wave: 0 triangle, 1 saw, 2 square, 3 pulse (duty).+// syncD ≥ 0: the master wrapped syncD samples ago → hard reset there. Returns the output+// (two samples late, the 4-point residual ring) and this oscillator's wrap distance.+inline float oscStep(pentad::Osc& o, double dt, int wave, float duty, float syncD, float& wrapOut) {+ const float gSaw = wave == 1 ? 1.0f : 0.0f;+ const float du = wave == 2 ? 0.5f : duty;+ const float gPul = wave >= 2 ? pentad::pulseZone(du) : 0.0f;+ const bool tri = wave == 0;+ wrapOut = -1.0f;+ if (syncD >= 0.0f) {+ const double p0 = o.ph;+ const float w1 = pentad::advance(o, dt * (1.0 - syncD), syncD, dt, du, gSaw, gPul);+ if (tri) triCorners(o, p0, w1, syncD, dt);+ const double pr = o.ph;+ o.ring.blep(syncD, -2.0f * static_cast<float>(pr) * gSaw); // saw snaps back to -1+ if (!o.hi && du > 0.0f) o.ring.blep(syncD, 2.0f * gPul); // pulse goes high+ if (tri) {+ o.ring.blep(syncD, -1.0f - triVal(pr)); // triangle restarts at -1+ if (pr >= 0.5) o.ring.blamp(syncD, static_cast<float>(8.0 * dt)); // falling → rising slope+ }+ o.hi = du > 0.0f;+ o.ph = 0.0;+ const float w2 = pentad::advance(o, dt * syncD, 0.0f, dt, du, gSaw, gPul);+ if (tri) triCorners(o, 0.0, w2, 0.0f, dt);+ } else {+ const double p0 = o.ph;+ wrapOut = pentad::advance(o, dt, 0.0f, dt, du, gSaw, gPul);+ if (tri) triCorners(o, p0, wrapOut, 0.0f, dt);+ }+ const float p = static_cast<float>(o.ph);+ float nv = gSaw * (2.0f * p - 1.0f) + gPul * ((o.hi ? 1.0f : -1.0f) - (2.0f * du - 1.0f));+ if (tri) nv += triVal(o.ph);+ o.ring.naive(nv);+ return o.ring.pop();+}++// Transistor-ladder core: four ZDF one-poles with a saturating resonance loop (Pentad's+// linearised-tanh solver). Low-pass is the 4th stage; 4-pole high-pass by mode mixing+// (u − 4y1 + 6y2 − 4y3 + y4), with the same resonant loop.+struct Ladder {+ float s[4] = { 0, 0, 0, 0 }, df[4] = { 0, 0, 0, 0 }, y4 = 0.0f;+ void clear() { for (int j = 0; j < 4; ++j) { s[j] = 0.0f; df[j] = 0.0f; } y4 = 0.0f; }+ float tick(float x, float g, float k, float comp, bool hp) {+ constexpr float kStageDrive = 0.3f, kLoopDrive = 2.2f;+ float G[4], S[4];+ for (int j = 0; j < 4; ++j) {+ const float a = g * pentad::tanhRatio(kStageDrive * df[j]);+ const float inv = 1.0f / (1.0f + a);+ G[j] = a * inv; S[j] = s[j] * inv;+ }+ const float Gt = G[0] * G[1] * G[2] * G[3];+ const float St = G[3] * (G[2] * (G[1] * S[0] + S[1]) + S[2]) + S[3];+ const float xin = x * (1.0f + comp * k);+ const float kf = k * pentad::tanhRatio(kLoopDrive * y4);+ float y3 = (Gt * xin + St) / (1.0f + kf * Gt);+ const float u = xin - kf * y3;+ const float y0 = G[0] * u + S[0], y1 = G[1] * y0 + S[1], y2 = G[2] * y1 + S[2];+ y3 = G[3] * y2 + S[3];+ df[0] = u - y0; df[1] = y0 - y1; df[2] = y1 - y2; df[3] = y2 - y3;+ s[0] = 2.0f * y0 - s[0]; s[1] = 2.0f * y1 - s[1]; s[2] = 2.0f * y2 - s[2]; s[3] = 2.0f * y3 - s[3];+ y4 = y3;+ if (!std::isfinite(s[0] + s[1] + s[2] + s[3])) { clear(); return 0.0f; }+ return hp ? (u - 4.0f * y0 + 6.0f * y1 - 4.0f * y2 + y3) : y3;+ }+};++// 2-pole TPT state-variable low-pass (the BBD's anti-alias / reconstruction filters).+struct SvfLp {+ float ic1 = 0.0f, ic2 = 0.0f;+ float tick(float x, float g, float k) {+ const float a1 = 1.0f / (1.0f + g * (g + k)), a2 = g * a1, a3 = g * a2;+ const float v3 = x - ic2;+ const float v1 = a1 * ic1 + a2 * v3;+ const float v2 = ic2 + a2 * ic1 + a3 * v3;+ ic1 = 2.0f * v1 - ic1; ic2 = 2.0f * v2 - ic2;+ return v2;+ }+ void clear() { ic1 = ic2 = 0.0f; }+};++} // namespace consort++class Consort final : public Instrument {+public:+ static constexpr int kSteps = 16, kCables = 12, kMaxVoices = 16, kOsc = 4;++ // Parameter layout (normalized 0..1). Order == persisted state layout — APPEND ONLY.+ enum Param {+ // --- controllers / voice / output (0..16) ---+ Tune = 0, Bend, ModWheel, Aftertouch, BendRange, Volume, Oversample, VoiceMode,+ TruePoly, MultiTrig, Unison, Drift, Glide, GlideType, GlideGated, VelVca, AtCut,+ // --- oscillators (17..30) ---+ O1Oct, O1Wave, O2Oct, O2Freq, O2Wave, O2Sync, O3Oct, O3Freq, O3Wave, O4Oct, O4Freq, O4Wave, O4Sync, Pw,+ // --- mixer (31..38) ---+ Mix1, Mix2, Mix3, Mix4, MixNoise, MixExt, NoiseColor, MixDrive,+ // --- dual ladder (39..45) ---+ FiltMode, Cutoff, Reso, Spacing, FEnvAmt, KbdTrk, BassComp,+ // --- envelopes (46..53) ---+ FAttack, FDecay, FSustain, FRelease, AAttack, ADecay, ASustain, ARelease,+ // --- LFO (54..60) ---+ LfoWave, LfoRate, LfoSync, LfoPitch, LfoCut, LfoPwm, LfoDest,+ // --- BBD delay (61..66) ---+ DlyTime, DlySpacing, DlyFb, DlyMix, DlyPing, DlyDigital,+ // --- sequencer / arpeggiator (67..74) ---+ SeqMode, SeqRate, SeqSwing, SeqOrder, SeqLatch, SeqLength, SeqRatchet, ArpOct,+ // --- 16 step types (75..90), 16 step pitches (91..106) ---+ StepType0,+ StepPitch0 = StepType0 + kSteps,+ // --- patch utilities (107..108) ---+ Atten1 = StepPitch0 + kSteps, Atten2,+ // --- 12 cables × (source, destination, depth) (109..144) ---+ Cable0,+ kNumParams = Cable0 + kCables * 3+ };++ // Scope telemetry layout (scopeRead): see publishTelemetry().+ enum Scope {+ ScMode = 0, ScActive, ScPeakL, ScPeakR, ScCpu, ScOs, ScRate, ScStep, ScBpm, ScLfo, ScEnv1, ScEnv2,+ ScOscNote, ScOscLvl = ScOscNote + kOsc, ScCutA = ScOscLvl + kOsc, ScCutB, ScDlyL, ScDlyR, ScSeqNote,+ kScopeN+ };++ Consort() {+ // "Init": four saws at 8' (a hair apart), PARA, stereo LP/LP a half-octave apart,+ // a moderate filter envelope, organ-ish amp envelope; delay dry, sequencer off.+ for (int i = 0; i < kNumParams; ++i) pn_[i].store(0.0f, std::memory_order_relaxed);+ set(Tune, 0.5f); set(Bend, 0.5f); set(ModWheel, 0.0f); set(Aftertouch, 0.0f);+ set(BendRange, 1.0f / 11.0f); set(Volume, 0.6f); set(Oversample, 0.5f); set(VoiceMode, 1.0f);+ set(TruePoly, 0.0f); set(MultiTrig, 1.0f); set(Unison, 1.0f); set(Drift, 0.25f);+ set(Glide, 0.0f); set(GlideType, 1.0f); set(GlideGated, 0.0f); set(VelVca, 0.0f); set(AtCut, 0.0f);+ set(O1Oct, 0.5f); set(O1Wave, 1.0f / 3.0f);+ set(O2Oct, 0.5f); set(O2Freq, 0.5f + 0.05f / 14.0f); set(O2Wave, 1.0f / 3.0f); set(O2Sync, 0.0f);+ set(O3Oct, 0.5f); set(O3Freq, 0.5f - 0.04f / 14.0f); set(O3Wave, 1.0f / 3.0f);+ set(O4Oct, 0.5f); set(O4Freq, 0.5f + 0.08f / 14.0f); set(O4Wave, 1.0f / 3.0f); set(O4Sync, 0.0f);+ set(Pw, 0.4f);+ set(Mix1, 0.75f); set(Mix2, 0.75f); set(Mix3, 0.75f); set(Mix4, 0.75f);+ set(MixNoise, 0.0f); set(MixExt, 0.0f); set(NoiseColor, 0.0f); set(MixDrive, 0.0f);+ set(FiltMode, 0.5f); set(Cutoff, 0.55f); set(Reso, 0.15f); set(Spacing, 0.5f + 0.5f / 6.0f);+ set(FEnvAmt, 0.66f); set(KbdTrk, 0.5f); set(BassComp, 0.0f);+ set(FAttack, 0.0f); set(FDecay, 0.45f); set(FSustain, 0.4f); set(FRelease, 0.4f);+ set(AAttack, 0.0f); set(ADecay, 0.45f); set(ASustain, 0.85f); set(ARelease, 0.35f);+ set(LfoWave, 0.0f); set(LfoRate, 0.5f); set(LfoSync, 0.0f); set(LfoPitch, 0.5f);+ set(LfoCut, 0.0f); set(LfoPwm, 0.0f); set(LfoDest, 0.0f);+ set(DlyTime, 0.62f); set(DlySpacing, 0.5f + 0.13f); set(DlyFb, 0.35f); set(DlyMix, 0.0f);+ set(DlyPing, 1.0f); set(DlyDigital, 0.0f);+ set(SeqMode, 0.0f); set(SeqRate, 0.6f); set(SeqSwing, 0.0f); set(SeqOrder, 0.0f);+ set(SeqLatch, 0.0f); set(SeqLength, 1.0f); set(SeqRatchet, 0.5f); set(ArpOct, 0.0f);+ static const int pat[kSteps] = { 0, 0, 12, 0, 7, 0, 12, 3, 0, 0, 12, 0, 7, 5, 10, 12 };+ for (int s = 0; s < kSteps; ++s) { set(StepType0 + s, 0.0f); set(StepPitch0 + s, 0.5f + pat[s] / 48.0f); }+ set(Atten1, 0.5f); set(Atten2, 0.5f);+ for (int c = 0; c < kCables; ++c) { set(Cable0 + c * 3, 0.0f); set(Cable0 + c * 3 + 1, 0.0f); set(Cable0 + c * 3 + 2, 0.75f); }++ initDecimators();+ dlyN_ = kDlyLen;+ dlyBuf_.reset(static_cast<float*>(std::calloc(static_cast<size_t>(kDlyLen) * 4, sizeof(float)))); // L, R, gain L, gain R+ resetAll();+ }++ int32_t kind() const override { return 15; }+ const char* displayName() const override { return "Nota Consort"; }++ // Deferred to the audio thread (render) so a device-rate change can't race a render.+ void setSampleRate(double sr) override { pendingRate_.store(sr > 0 ? sr : 44100.0, std::memory_order_relaxed); }++ int32_t activeVoiceCount() const override { return static_cast<int32_t>(tele_[ScActive].load(std::memory_order_relaxed)); }+ int32_t scopeRead(float* out, int32_t maxN) const override {+ const int n = std::min<int>(maxN, kScopeN);+ for (int i = 0; i < n; ++i) out[i] = tele_[i].load(std::memory_order_relaxed);+ return n;+ }+ int32_t heldNotes(int32_t* out, int32_t maxN) const override {+ const int n = std::min<int>(keyN_, maxN);+ for (int i = 0; i < n; ++i) out[i] = keys_[i];+ return n;+ }++ // ---- parameters -----------------------------------------------------------+ // Display names group by the part before the last space (the automation menu nests on it).+ static const std::vector<std::string>& idTable() {+ static const std::vector<std::string> t = [] {+ std::vector<std::string> v = {+ "tune", "bend", "modwheel", "aftertouch", "bendrange", "volume", "oversample", "voicemode",+ "truepoly", "multitrig", "unison", "drift", "glide", "glidetype", "glidegated", "velvca", "atcut",+ "o1oct", "o1wave", "o2oct", "o2freq", "o2wave", "o2sync", "o3oct", "o3freq", "o3wave", "o4oct", "o4freq", "o4wave", "o4sync", "pw",+ "mix1", "mix2", "mix3", "mix4", "mixnoise", "mixext", "noisecolor", "mixdrive",+ "filtmode", "cutoff", "reso", "spacing", "fenvamt", "kbdtrk", "basscomp",+ "fattack", "fdecay", "fsustain", "frelease", "aattack", "adecay", "asustain", "arelease",+ "lfowave", "lforate", "lfosync", "lfopitch", "lfocut", "lfopwm", "lfodest",+ "dlytime", "dlyspacing", "dlyfb", "dlymix", "dlyping", "dlydigital",+ "seqmode", "seqrate", "seqswing", "seqorder", "seqlatch", "seqlen", "seqratchet", "arpoct" };+ for (int s = 0; s < kSteps; ++s) v.push_back("st" + std::to_string(s + 1));+ for (int s = 0; s < kSteps; ++s) v.push_back("sp" + std::to_string(s + 1));+ v.push_back("atten1"); v.push_back("atten2");+ for (int c = 0; c < kCables; ++c) {+ const std::string n = std::to_string(c + 1);+ v.push_back("c" + n + "src"); v.push_back("c" + n + "dst"); v.push_back("c" + n + "amt");+ }+ return v;+ }();+ return t;+ }+ static const std::vector<std::string>& nameTable() {+ static const std::vector<std::string> t = [] {+ std::vector<std::string> v = {+ "Master Tune", "Control Pitch-Bend", "Control Mod-Wheel", "Control Aftertouch", "Control Bend-Range",+ "Output Volume", "Output Oversampling", "Voice Mode",+ "Voice True-Poly", "Voice Multi-Trig", "Voice Unison-Detune", "Voice Drift", "Voice Glide-Time",+ "Voice Glide-Type", "Voice Glide-Gated", "Output Velocity-VCA", "Output Aftertouch-Cutoff",+ "Osc 1 Octave", "Osc 1 Wave", "Osc 2 Octave", "Osc 2 Frequency", "Osc 2 Wave", "Osc 2 Sync",+ "Osc 3 Octave", "Osc 3 Frequency", "Osc 3 Wave", "Osc 4 Octave", "Osc 4 Frequency", "Osc 4 Wave", "Osc 4 Sync",+ "Osc Pulse-Width",+ "Mixer Osc-1", "Mixer Osc-2", "Mixer Osc-3", "Mixer Osc-4", "Mixer Noise", "Mixer Ext", "Mixer Noise-Color", "Mixer Drive",+ "Filter Mode", "Filter Cutoff", "Filter Resonance", "Filter Spacing", "Filter Env-Amount", "Filter Key-Track", "Filter Bass-Comp",+ "Filter-Env Attack", "Filter-Env Decay", "Filter-Env Sustain", "Filter-Env Release",+ "Amp-Env Attack", "Amp-Env Decay", "Amp-Env Sustain", "Amp-Env Release",+ "LFO Wave", "LFO Rate", "LFO Tempo-Sync", "LFO Pitch", "LFO Cutoff", "LFO PWM", "LFO Destination",+ "Delay Time", "Delay Spacing", "Delay Feedback", "Delay Mix", "Delay Ping-Pong", "Delay Digital",+ "Seq Mode", "Seq Rate", "Seq Swing", "Seq Order", "Seq Latch", "Seq Length", "Seq Ratchet", "Seq Arp-Octaves" };+ auto two = [](int i) { return (i < 10 ? "0" : "") + std::to_string(i); };+ for (int s = 0; s < kSteps; ++s) v.push_back("Seq-Type Step-" + two(s + 1));+ for (int s = 0; s < kSteps; ++s) v.push_back("Seq-Pitch Step-" + two(s + 1));+ v.push_back("Patch Atten-1"); v.push_back("Patch Atten-2");+ for (int c = 0; c < kCables; ++c) {+ const std::string n = two(c + 1);+ v.push_back("Patch-Source Cable-" + n); v.push_back("Patch-Dest Cable-" + n); v.push_back("Patch-Depth Cable-" + n);+ }+ return v;+ }();+ return t;+ }+ static std::string paramId(int i) { return (i >= 0 && i < kNumParams) ? idTable()[static_cast<size_t>(i)] : std::string(); }++ int32_t pluginParamCount() const override { return kNumParams; }+ std::string pluginParamId(int32_t i) const override { return paramId(i); }+ std::string pluginParamName(int32_t i) const override { return (i >= 0 && i < kNumParams) ? nameTable()[static_cast<size_t>(i)] : std::string(); }+ float pluginParamGet(int32_t i) const override {+ return (i >= 0 && i < kNumParams) ? pn_[i].load(std::memory_order_relaxed) : 0.0f;+ }+ void pluginParamSet(int32_t i, float v) override {+ if (i >= 0 && i < kNumParams && std::isfinite(v)) pn_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed);+ }+ int32_t pluginParamIndexOfId(const std::string& id) const override {+ const auto& t = idTable();+ for (int32_t i = 0; i < kNumParams; ++i) if (t[static_cast<size_t>(i)] == id) return i;+ return -1;+ }++ // ---- project state (kNumParams normalized floats, little-endian) ------------+ std::vector<uint8_t> getState() const override {+ std::vector<uint8_t> b(kNumParams * sizeof(float));+ for (int i = 0; i < kNumParams; ++i) {+ const float v = pn_[i].load(std::memory_order_relaxed);+ std::memcpy(b.data() + i * sizeof(float), &v, sizeof(float));+ }+ return b;+ }+ void setState(const uint8_t* data, int32_t size) override {+ if (!data) return;+ const int n = std::min<int>(kNumParams, size / static_cast<int>(sizeof(float)));+ for (int i = 0; i < n; ++i) {+ float v; std::memcpy(&v, data + i * sizeof(float), sizeof(float));+ if (std::isfinite(v)) pn_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed);+ }+ }+ std::shared_ptr<Instrument> clone() const override {+ auto s = std::make_shared<Consort>();+ for (int i = 0; i < kNumParams; ++i) s->pn_[i].store(pn_[i].load(std::memory_order_relaxed), std::memory_order_relaxed);+ s->setSampleRate(pendingRate_.load(std::memory_order_relaxed));+ return s;+ }++ // ---- musical mappings (mirrored by the editor's readouts) ------------------+ static int octaveOf(float v) { return std::clamp(static_cast<int>(std::lround(v * 4.0f)), 0, 4) - 2; } // 32'..2'+ static float freqSemisOf(float v) { return (v - 0.5f) * 14.0f; } // ±7 st+ static int waveOf(float v) { return std::clamp(static_cast<int>(std::lround(v * 3.0f)), 0, 3); }+ static float dutyOf(float v) { return 0.5f - 0.45f * std::clamp(v, 0.0f, 1.0f); }+ static float cutoffHzOf(float v) { return 20.0f * std::pow(1000.0f, std::clamp(v, 0.0f, 1.0f)); }+ static float spacingOctOf(float v) { return (v - 0.5f) * 6.0f; }+ static float envAmtOctOf(float v) { return (v - 0.5f) * 2.0f * 7.0f; }+ static float attackSecOf(float v) { return static_cast<float>(expMap(v, 0.001, 10.0)); }+ static float decaySecOf(float v) { return static_cast<float>(expMap(v, 0.003, 15.0)); }+ static float glideSecOf(float v) { return v < 0.002f ? 0.0f : static_cast<float>(expMap(v, 0.005, 5.0)); }+ static float lfoHzOf(float v) { return static_cast<float>(expMap(v, 0.05, 30.0)); }+ static float lfoCentsOf(float v) { const float b = (v - 0.5f) * 2.0f; return b * std::fabs(b) * 1200.0f; }+ static float dlySecOf(float v) { return static_cast<float>(expMap(v, 0.02, 1.5)); }+ static float dlySpacingOf(float v) { return (v - 0.5f) * 2.0f * 0.5f; }+ static int bendRangeOf(float v) { return 1 + std::clamp(static_cast<int>(std::lround(v * 11.0f)), 0, 11); }+ static float volumeGainOf(float v) { return 2.0f * v * v; }+ static int seqLengthOf(float v) { return 1 + std::clamp(static_cast<int>(std::lround(v * (kSteps - 1))), 0, kSteps - 1); }+ static int ratchetOf(float v) { return 2 + std::clamp(static_cast<int>(std::lround(v * 2.0f)), 0, 2); }+ static int arpOctOf(float v) { return 1 + std::clamp(static_cast<int>(std::lround(v * 2.0f)), 0, 2); }+ static float swingOf(float v) { return 0.5f + 0.25f * std::clamp(v, 0.0f, 1.0f); }+ static int stepTypeOf(float v) { return std::clamp(static_cast<int>(std::lround(v * 3.0f)), 0, 3); } // note/ratchet/tie/rest+ static int stepPitchOf(float v) { return std::clamp(static_cast<int>(std::lround((v - 0.5f) * 48.0f)), -24, 24); }+ static int jackOf(float v) { return std::clamp(static_cast<int>(std::lround(v * consort::kJackScale)), 0, consort::kJackScale); }+ static float depthOf(float v) { return (v - 0.5f) * 2.0f; }+ static constexpr int kSeqRates = 6;+ static double seqRateBeats(float v) {+ static const double b[kSeqRates] = { 1.0, 0.5, 1.0 / 3.0, 0.25, 1.0 / 6.0, 0.125 }; // 1/4 1/8 1/8T 1/16 1/16T 1/32+ return b[std::clamp(static_cast<int>(std::lround(v * (kSeqRates - 1))), 0, kSeqRates - 1)];+ }+ static constexpr int kSyncDivs = 14;+ static double syncBeatsOf(float v) { // LFO cycle length in beats (quarter notes)+ static const double b[kSyncDivs] = { 32., 16., 8., 4., 2., 1.5, 1., 0.75, 2. / 3., 0.5, 1. / 3., 0.25, 1. / 6., 0.125 };+ return b[std::clamp(static_cast<int>(std::lround(v * (kSyncDivs - 1))), 0, kSyncDivs - 1)];+ }++ // ---- transport (play edge → reseed for determinism; LFO / sequencer sync) ----+ void setTransport(double beatStart, double samplesPerBeat, bool playing) override {+ const double pos = beatStart * samplesPerBeat;+ const bool jumped = playing && tPlaying_ && std::fabs(pos - (tPos_ + tFrames_)) > 2.0;+ if (jumped) resetAll();+ else if (playing && !tPlaying_) {+ bool any = false;+ for (int v = 0; v < kMaxVoices; ++v) any |= voices_[v].active;+ if (!any && !seqRun_) resetAll();+ }+ tBeat_ = beatStart; tSpb_ = samplesPerBeat; tFresh_ = true;+ tPos_ = pos; tFrames_ = 0.0;+ if (playing != tPlaying_) nextEvBeat_ = -1e300; // re-grid the sequencer on the new clock+ tPlaying_ = playing;+ }++ // ---- note events ----------------------------------------------------------------+ void noteOn(int32_t pitch, float velocity) override {+ syncStructure();+ const float vel = std::clamp(velocity, 0.0f, 1.0f);+ pushKey(pitch);+ if (seqMode() != 0) { seqKeyOn(pitch, vel); return; }+ playOn(pitch, vel);+ }+ void noteOff(int32_t pitch) override {+ syncStructure();+ removeKey(pitch);+ if (seqMode() != 0) { seqKeyOff(pitch); return; }+ playOff(pitch);+ }+ // Stop / loop wrap: silence the voices and the sequencer; the delay tail keeps ringing.+ void allNotesOff() override { resetVoices(); }++ // ---- render ---------------------------------------------------------------------+ void render(float* out, int32_t frames) override {+ FtzGuard ftz;+ const auto t0 = std::chrono::steady_clock::now();+ const double pr = pendingRate_.load(std::memory_order_relaxed);+ if (pr != sampleRate_) { // voices keep playing; only rate-derived state restarts+ sampleRate_ = pr;+ fadeLen_ = std::max(1, static_cast<int>(0.004 * sampleRate_));+ for (int c = 0; c < 2; ++c) { dnSteep_[c].clear_buffers(); dnMid_[c].clear_buffers(); }+ smoothInit_ = false;+ setupDelayRate();+ }+ for (int32_t done = 0; done < frames;) {+ const int n = std::min<int>(kChunk, frames - done);+ renderChunk(out + done * 2, n); // advances tFrames_+ done += n;+ }+ const double el = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();+ const double avail = frames / sampleRate_;+ if (avail > 0.0) cpu_ += 0.05 * (el / avail - cpu_);+ publishTelemetry();+ }++private:+ static constexpr int kChunk = 64;+ static constexpr int kMaxOs = 4;+ static constexpr int kDlyLen = 1 << 17; // per channel, at a line rate ≤ 50 kHz+ static constexpr double kPi = 3.14159265358979323846;++ struct Voice {+ bool active = false, gate = false, retrig = false;+ int note = 60; float vel = 0.8f;+ uint64_t order = 0;+ // stolen-voice handoff (poly)+ int pendNote = -1, fade = 0; float pendVel = 0.0f; bool pendGlide = false;+ // per-oscillator pitch (semitones), glide, slot gain (paraphonic fades)+ float pitch[kOsc] = { 60, 60, 60, 60 }, tgt[kOsc] = { 60, 60, 60, 60 }, rate[kOsc] = { 0, 0, 0, 0 };+ bool hasPitch[kOsc] = { false, false, false, false };+ float g[kOsc] = { 0, 0, 0, 0 }, gT[kOsc] = { 0, 0, 0, 0 };+ float det[kOsc] = { 0, 0, 0, 0 };+ // envelopes: stage 0 idle, 1 attack, 2 decay/sustain, 3 release+ float fenv = 0.0f, aenv = 0.0f; int fst = 0, ast = 0;+ bool g1s = false, g2s = false; // patched gate-in state (edge detection)+ pentad::Osc osc[kOsc];+ consort::Ladder fa, fb;+ pentad::Adaa sat;+ // patch: previous-sample sources and utility nodes, gate inputs+ float oPrev[kOsc] = { 0, 0, 0, 0 }, fPrev = 0.0f, vPrev = 0.0f;+ float uIn[3] = { 0, 0, 0 }; // atten 1, atten 2, sum (inputs, previous sample)+ float gIn1 = 0.0f, gIn2 = 0.0f;+ // vintage: static per-osc spread + slow random walk+ float oOff[kOsc] = { 0, 0, 0, 0 }, oCut = 0.0f;+ float w[kOsc + 1] = { 0, 0, 0, 0, 0 }, wt[kOsc + 1] = { 0, 0, 0, 0, 0 }; int wCount = 0;+ pentad::Rng rng;+ // previous base-rate controls, interpolated across the oversampled sub-steps+ float pP[kOsc] = { 0, 0, 0, 0 }, pCa = 0, pCb = 0, pAmp = 0, pDuty = 0.5f;+ bool fresh = true;+ float cutA = 0.0f, cutB = 0.0f; // telemetry (log2 Hz)+ float level = 0.0f;+ };++ struct FtzGuard {+#if defined(NOTA_CONSORT_FTZ_X86)+ unsigned int old; FtzGuard() : old(_mm_getcsr()) { _mm_setcsr(old | 0x8040u); } ~FtzGuard() { _mm_setcsr(old); }+#elif defined(NOTA_CONSORT_FTZ_ARM)+ uint64_t old = 0;+ FtzGuard() { asm volatile("mrs %0, fpcr" : "=r"(old)); const uint64_t n = old | (1ull << 24); asm volatile("msr fpcr, %0" : : "r"(n)); }+ ~FtzGuard() { asm volatile("msr fpcr, %0" : : "r"(old)); }+#endif+ };+ struct FreeDel { void operator()(float* p) const { std::free(p); } };++ void set(int p, float v) { pn_[p].store(v, std::memory_order_relaxed); }+ float get(int p) const { return pn_[p].load(std::memory_order_relaxed); }+ static double expMap(double v, double lo, double hi) { return lo * std::pow(hi / lo, std::clamp(v, 0.0, 1.0)); }+ static float coefOf(float tau, double sr) { return 1.0f - static_cast<float>(std::exp(-1.0 / (std::max(tau, 1e-5f) * sr))); }+ // 0..2 = Mono / Duo / Para, 3 = true poly.+ int structMode() const { return get(TruePoly) > 0.5f ? 3 : std::clamp(static_cast<int>(std::lround(get(VoiceMode) * 2.0f)), 0, 2); }+ int seqMode() const { return std::clamp(static_cast<int>(std::lround(get(SeqMode) * 2.0f)), 0, 2); }+ static int slotsOf(int mode) { return mode == 0 ? 1 : mode == 1 ? 2 : 4; }+ static int slotOfOsc(int k, int S) { return S == 1 ? 0 : S == 2 ? k / 2 : k; }++ // ---- key lists ------------------------------------------------------------------+ static void listPush(int* a, int& n, int p) { for (int i = 0; i < n; ++i) if (a[i] == p) { for (int j = i; j < n - 1; ++j) a[j] = a[j + 1]; --n; break; } if (n < 128) a[n++] = p; }+ static bool listRemove(int* a, int& n, int p) { int w = 0; bool f = false; for (int r = 0; r < n; ++r) { if (a[r] == p) f = true; else a[w++] = a[r]; } n = w; return f; }+ void pushKey(int p) { listPush(keys_, keyN_, p); }+ void removeKey(int p) { listRemove(keys_, keyN_, p); }++ // ===================================================================================+ // Voice layer: playOn / playOff (from the keyboard, or from the sequencer)+ // ===================================================================================+ void playOn(int p, float vel) {+ if (structMode() == 3) polyOn(p, vel); else paraOn(p, vel);+ }+ void playOff(int p) {+ if (structMode() == 3) polyOff(p); else paraOff(p);+ }++ // Per-oscillator glide target. Linear types store a rate (semitones / sample).+ void setOscTarget(Voice& V, int k, int note, bool glide) {+ const float tg = static_cast<float>(note);+ const float T = glideSecOf(get(Glide));+ if (!glide || !V.hasPitch[k] || T <= 0.0f) { V.pitch[k] = V.tgt[k] = tg; V.rate[k] = 0.0f; V.hasPitch[k] = true; return; }+ V.tgt[k] = tg;+ const int type = std::clamp(static_cast<int>(std::lround(get(GlideType) * 2.0f)), 0, 2);+ const double spT = T * sampleRate_;+ if (type == 0) V.rate[k] = static_cast<float>(12.0 / spT); // LCR: T per octave+ else if (type == 1) V.rate[k] = static_cast<float>(std::fabs(tg - V.pitch[k]) / spT); // LCT: always T+ else V.rate[k] = -1.0f; // EXP+ }+ bool glideAllowed(bool legato) const { return glideSecOf(get(Glide)) > 0.0f && (get(GlideGated) < 0.5f || legato); }++ static void trigger(Voice& V) { V.retrig = true; }+ static void release(Voice& V) { V.gate = false; V.retrig = false; if (V.fst) V.fst = 3; if (V.ast) V.ast = 3; }++ // A sleeping voice wakes: free-running oscillators land at arbitrary phases; the filter /+ // BLEP state it slept with is stale and cleared.+ void wake(Voice& V) {+ V.active = true; V.fresh = true;+ const float duty = dutyOf(get(Pw));+ for (int k = 0; k < kOsc; ++k) {+ V.osc[k].ph += V.rng.uni(); V.osc[k].ph -= std::floor(V.osc[k].ph);+ V.osc[k].hi = V.osc[k].ph < duty; V.osc[k].ring.clear();+ V.oPrev[k] = 0.0f;+ }+ V.fa.clear(); V.fb.clear(); V.sat.reset();+ V.fPrev = V.vPrev = 0.0f; V.uIn[0] = V.uIn[1] = V.uIn[2] = 0.0f; V.gIn1 = V.gIn2 = 0.0f;+ V.g1s = V.g2s = false;+ }++ // ---- paraphonic layer (Mono / Duo / Para: voice 0, oscillators grouped in slots) ----+ void paraOn(int p, float vel) {+ const bool others = pHeldN_ > 0;+ listPush(pHeld_, pHeldN_, p);+ Voice& V = voices_[0];+ V.vel = vel; V.note = p; V.order = ++orderCtr_;+ focus_ = 0;+ assignSlots(others);+ V.gate = true;+ if (!others || get(MultiTrig) > 0.5f) trigger(V);+ if (!V.active) wake(V);+ }+ void paraOff(int p) {+ if (!listRemove(pHeld_, pHeldN_, p)) return;+ Voice& V = voices_[0];+ if (pHeldN_ == 0) { release(V); return; } // slots keep their pitch for the release tail+ V.note = pHeld_[pHeldN_ - 1];+ assignSlots(true);+ }+ // The most recent S held notes own the S slots (a note keeps its slot while held; new+ // notes rotate into free slots). With Unison on, empty slots double the held notes.+ void assignSlots(bool legato) {+ Voice& V = voices_[0];+ const int S = slotsOf(structMode());+ const int nw = std::min(S, pHeldN_);+ int want[4] = { -1, -1, -1, -1 };+ for (int j = 0; j < nw; ++j) want[j] = pHeld_[pHeldN_ - nw + j];+ int na[4] = { -1, -1, -1, -1 }; bool used[4] = { false, false, false, false };+ for (int s = 0; s < S; ++s) {+ if (slotDbl_[s] || slotNote_[s] < 0) continue;+ for (int j = 0; j < nw; ++j) if (!used[j] && want[j] == slotNote_[s]) { na[s] = want[j]; used[j] = true; break; }+ }+ for (int j = 0; j < nw; ++j) {+ if (used[j]) continue;+ for (int t = 0; t < S; ++t) { const int s = (rr_ + t) % S; if (na[s] < 0) { na[s] = want[j]; used[j] = true; rr_ = (s + 1) % S; break; } }+ }+ bool dbl[4] = { false, false, false, false };+ if (get(Unison) > 0.5f && nw > 0) {+ int k = 0;+ for (int s = 0; s < S; ++s) if (na[s] < 0) { na[s] = want[nw - 1 - (k % nw)]; dbl[s] = true; ++k; }+ }+ for (int s = 0; s < 4; ++s) { slotNote_[s] = s < S ? na[s] : -1; slotDbl_[s] = s < S && dbl[s]; }+ const bool gl = glideAllowed(legato);+ for (int k = 0; k < kOsc; ++k) {+ const int note = na[slotOfOsc(k, S)];+ if (note >= 0) { setOscTarget(V, k, note, gl); V.gT[k] = 1.0f; }+ else V.gT[k] = 0.0f;+ }+ }++ // ---- true poly layer (16 full voices; oldest-note steal with a short fade) -----+ void polyOn(int p, float vel) {+ const bool others = pHeldN_ > 0;+ listPush(pHeld_, pHeldN_, p);+ const bool glide = glideAllowed(others);+ int v = -1;+ for (int k = 0; k < kMaxVoices; ++k) { const Voice& V = voices_[k]; if (V.active && V.gate && V.note == p && V.pendNote < 0) { v = k; break; } }+ bool fade = false;+ if (v < 0) v = allocate(fade);+ Voice& V = voices_[v];+ if (fade) { V.pendNote = p; V.pendVel = vel; V.pendGlide = glide; V.fade = fadeLen_; V.gate = false; return; }+ startPoly(v, p, vel, glide);+ }+ void startPoly(int v, int p, float vel, bool glide) {+ Voice& V = voices_[v];+ V.note = p; V.vel = vel; V.gate = true; V.order = ++orderCtr_;+ for (int k = 0; k < kOsc; ++k) { setOscTarget(V, k, p, glide); V.gT[k] = 1.0f; V.g[k] = 1.0f; }+ trigger(V);+ focus_ = v;+ if (!V.active) wake(V);+ }+ void polyOff(int p) {+ listRemove(pHeld_, pHeldN_, p);+ for (int v = 0; v < kMaxVoices; ++v) {+ Voice& V = voices_[v];+ if (V.gate && V.note == p) release(V);+ if (V.pendNote == p) V.pendNote = -1;+ }+ }+ int allocate(bool& fade) {+ fade = false;+ int best = -1; uint64_t bo = ~0ull;+ for (int v = 0; v < kMaxVoices; ++v) if (!voices_[v].active && voices_[v].pendNote < 0 && voices_[v].order < bo) { bo = voices_[v].order; best = v; }+ if (best >= 0) return best;+ for (int v = 0; v < kMaxVoices; ++v) if (!voices_[v].gate && voices_[v].pendNote < 0 && voices_[v].order < bo) { bo = voices_[v].order; best = v; }+ if (best >= 0) return best;+ for (int v = 0; v < kMaxVoices; ++v) if (voices_[v].pendNote < 0 && voices_[v].order < bo) { bo = voices_[v].order; best = v; }+ if (best < 0) best = 0;+ fade = true;+ return best;+ }++ // ===================================================================================+ // Sequencer / arpeggiator (drives playOn / playOff, sample-accurate)+ // ===================================================================================+ const int* poolArr() const { return get(SeqLatch) > 0.5f ? lat_ : phys_; }+ int poolN() const { return get(SeqLatch) > 0.5f ? latN_ : physN_; }++ void seqKeyOn(int p, float vel) {+ const bool latch = get(SeqLatch) > 0.5f;+ if (latch && physN_ == 0) latN_ = 0; // a fresh chord replaces the latched one+ listPush(phys_, physN_, p);+ if (latch) listPush(lat_, latN_, p);+ seqVel_ = vel; seqBase_ = p;+ if (!seqRun_ && poolN() > 0) seqStart();+ }+ void seqKeyOff(int p) {+ listRemove(phys_, physN_, p);+ if (get(SeqLatch) > 0.5f) return;+ if (physN_ == 0) { seqStop(); return; }+ seqBase_ = phys_[physN_ - 1];+ }+ void seqStart() {+ seqRun_ = true; curN_ = LLONG_MIN; arpPos_ = -1; seqIntBeat_ = 0.0; nextEvBeat_ = -1e300;+ curType_ = 3; curSub_ = 0;+ }+ void seqStop() {+ if (seqNote_ >= 0) { playOff(seqNote_); seqNote_ = -1; }+ seqRun_ = false; curN_ = LLONG_MIN; curIdx_ = -1; seqGateV_ = 0.0f;+ }+ double spb() const { return tSpb_ > 1.0 ? tSpb_ : sampleRate_ * 0.5; }+ double beatNow() const { return tPlaying_ && tSpb_ > 1.0 ? tBeat_ + tFrames_ / tSpb_ : seqIntBeat_; }++ int stepIndexOf(long long n) const {+ const int len = seqLengthOf(get(SeqLength));+ const int ord = std::clamp(static_cast<int>(std::lround(get(SeqOrder) * 2.0f)), 0, 2);+ const long long m = ((n % len) + len) % len;+ if (seqMode() == 2 || ord == 0) return static_cast<int>(m); // ARP: order walks the chord+ if (ord == 1) return len - 1 - static_cast<int>(m);+ return static_cast<int>(pentad::hash32(static_cast<uint32_t>(n) * 2654435761U ^ 0x51ED27U) % static_cast<uint32_t>(len));+ }+ int stepType(int idx) const { return stepTypeOf(get(StepType0 + idx)); }+ int stepPitch(int idx) const { return stepPitchOf(get(StepPitch0 + idx)); }++ int arpNext() {+ int srt[128]; const int n = poolN();+ if (n <= 0) return seqBase_;+ std::memcpy(srt, poolArr(), sizeof(int) * static_cast<size_t>(n));+ std::sort(srt, srt + n);+ const int oct = arpOctOf(get(ArpOct));+ const int cnt = n * oct;+ const int ord = std::clamp(static_cast<int>(std::lround(get(SeqOrder) * 2.0f)), 0, 2);+ int j;+ if (ord == 2) j = static_cast<int>(pentad::hash32(static_cast<uint32_t>(++arpCtr_) * 0x9E3779B9U ^ 0xA11CE5U) % static_cast<uint32_t>(cnt));+ else { arpPos_ = (arpPos_ + 1) % cnt; j = ord == 1 ? cnt - 1 - arpPos_ : arpPos_; }+ seqPitchV_ = static_cast<float>(12 * (j / n) + srt[j % n] - srt[0]) / 60.0f;+ return srt[j % n] + 12 * (j / n);+ }+ int seqPitchFor(int idx) {+ if (seqMode() == 2) return std::clamp(arpNext(), 0, 127);+ const int sp = stepPitch(idx);+ seqPitchV_ = static_cast<float>(sp) / 60.0f;+ return std::clamp(seqBase_ + sp, 0, 127);+ }+ void seqNoteOn(int p) { if (seqNote_ >= 0) playOff(seqNote_); seqNote_ = p; playOn(p, seqVel_); seqGateV_ = 1.0f; }+ void seqNoteOff() { if (seqNote_ >= 0) { playOff(seqNote_); seqNote_ = -1; } seqGateV_ = 0.0f; }++ // Fire every event due at the current position.+ void seqService() {+ if (!seqRun_) return;+ const double b = beatNow();+ for (int guard = 0; guard < 8 && b + 1e-9 >= nextEvBeat_; ++guard) seqProcess(b);+ }+ void seqProcess(double b) {+ constexpr double eps = 1e-9;+ const double rb = seqRateBeats(get(SeqRate));+ const double sw = swingOf(get(SeqSwing));+ const double pair = std::floor((b + eps) / (2.0 * rb));+ const double p = b - pair * 2.0 * rb;+ const bool odd = p + eps >= 2.0 * rb * sw;+ const long long n = static_cast<long long>(pair) * 2 + (odd ? 1 : 0);+ const double sb = pair * 2.0 * rb + (odd ? 2.0 * rb * sw : 0.0);+ const double sl = odd ? 2.0 * rb * (1.0 - sw) : 2.0 * rb * sw;+ const int R = ratchetOf(get(SeqRatchet));+ if (n != curN_) {+ curN_ = n;+ const int idx = stepIndexOf(n);+ const int nextT = stepType(stepIndexOf(n + 1));+ curIdx_ = idx; clk_ = std::max(1, static_cast<int>(0.005 * sampleRate_));+ const int t = stepType(idx);+ const double gateEnd = nextT == 2 ? 1e300 : sb + 0.6 * sl;+ if (t == 3) { seqNoteOff(); curType_ = 3; }+ else if (t == 2) {+ if (seqNote_ < 0) curType_ = 3;+ else { curType_ = 2; offBeat_ = gateEnd; }+ } else if (t == 1) {+ seqNoteOn(seqPitchFor(idx)); curType_ = 1; curSub_ = 0; curPitch_ = seqNote_;+ offBeat_ = sb + 0.5 * sl / R;+ } else {+ seqNoteOn(seqPitchFor(idx)); curType_ = 0; offBeat_ = gateEnd;+ }+ } else if (curType_ == 1) {+ const int k = static_cast<int>(std::floor((b - sb + eps) / (sl / R)));+ if (k != curSub_ && k < R) {+ curSub_ = k; clk_ = std::max(1, static_cast<int>(0.005 * sampleRate_));+ seqNoteOn(curPitch_);+ offBeat_ = sb + (k + 0.5) * sl / R;+ }+ }+ if (seqNote_ >= 0 && b + eps >= offBeat_) seqNoteOff();+ double nx = sb + sl;+ if (curType_ == 1) { const double sub = sb + (curSub_ + 1) * sl / R; if (sub < nx - eps) nx = sub; }+ if (seqNote_ >= 0 && offBeat_ < nx) nx = offBeat_;+ nextEvBeat_ = std::max(nx, b + 1e-7);+ }+ int seqSamplesToNext() const {+ if (!seqRun_) return INT_MAX;+ const double d = (nextEvBeat_ - beatNow()) * spb();+ if (d <= 0.0) return 0;+ return d > 1e9 ? INT_MAX : static_cast<int>(std::ceil(d - 1e-6));+ }++ // ===================================================================================+ // Structure / reset+ // ===================================================================================+ // Mode changes are applied before any note event or render sees them (audio thread):+ // a voice-structure or sequencer switch releases everything; turning latch off drops+ // the latched chord.+ void syncStructure() {+ const int st = structMode();+ if (st != lastStruct_) {+ for (auto& V : voices_) if (V.gate || V.pendNote >= 0) { release(V); V.pendNote = -1; }+ pHeldN_ = 0; rr_ = 0;+ for (int s = 0; s < 4; ++s) { slotNote_[s] = -1; slotDbl_[s] = false; }+ if (seqNote_ >= 0) seqNote_ = -1;+ lastStruct_ = st;+ }+ const int sm = seqMode();+ if (sm != lastSeq_) {+ seqStop();+ physN_ = latN_ = 0;+ for (auto& V : voices_) if (V.gate) release(V);+ pHeldN_ = 0;+ lastSeq_ = sm;+ }+ if (get(SeqLatch) < 0.5f && latN_ > 0) { latN_ = 0; if (seqRun_ && physN_ == 0) seqStop(); }+ }+ void resetVoices() {+ for (int v = 0; v < kMaxVoices; ++v) {+ Voice& V = voices_[v];+ const pentad::Rng rng = V.rng;+ const float oOff[kOsc] = { V.oOff[0], V.oOff[1], V.oOff[2], V.oOff[3] }; const float oCut = V.oCut;+ V = Voice{};+ V.rng = rng; V.oCut = oCut;+ for (int k = 0; k < kOsc; ++k) { V.oOff[k] = oOff[k]; V.osc[k].ph = V.rng.uni(); }+ V.wCount = 1 + static_cast<int>(V.rng.next() % 4096u);+ }+ pHeldN_ = 0; keyN_ = 0; rr_ = 0; physN_ = latN_ = 0;+ for (int s = 0; s < 4; ++s) { slotNote_[s] = -1; slotDbl_[s] = false; }+ seqRun_ = false; seqNote_ = -1; curN_ = LLONG_MIN; curIdx_ = -1; seqGateV_ = 0.0f; seqPitchV_ = 0.0f; clk_ = 0;+ lastStruct_ = structMode(); lastSeq_ = seqMode();+ fadeLen_ = std::max(1, static_cast<int>(0.004 * sampleRate_));+ }+ void resetAll() {+ for (int v = 0; v < kMaxVoices; ++v) {+ Voice& V = voices_[v];+ V.rng.seed(pentad::hash32(0xC0A5E7u ^ pentad::hash32(static_cast<uint32_t>(v) * 0x9E3779B9U + 1U)));+ for (int k = 0; k < kOsc; ++k) V.oOff[k] = V.rng.bi();+ V.oCut = V.rng.bi();+ }+ resetVoices();+ orderCtr_ = 0; focus_ = 0; arpCtr_ = 0;+ lfoPh_ = 0.0; lfoRnd0_ = lfoRnd1_ = 0.0f; tFresh_ = true;+ noiseRng_.seed(0xA5A5A5A5U); lfoRng_.seed(0x5A5A5A5AU); dlyRng_.seed(0x3C3C3C3CU);+ pk0_ = pk1_ = pk2_ = 0.0f;+ for (int c = 0; c < 2; ++c) { dnSteep_[c].clear_buffers(); dnMid_[c].clear_buffers(); }+ smoothInit_ = false;+ peakL_ = peakR_ = 0.0f;+ clearDelay();+ }+ void initDecimators() {+ static const double steep[12] = {+ 0.017347915108876406, 0.067150480426919179, 0.14330738338179819, 0.23745131944299824,+ 0.34085550201503761, 0.44601111310335906, 0.54753112652956148, 0.6423859124721446,+ 0.72968928615804163, 0.81029959388029904, 0.88644514917318362, 0.96150605146543733 };+ static const double mid[5] = {+ 0.029113887601773612, 0.11638402872809682, 0.26337786480329456, 0.47885453461538624,+ 0.78984065611473109 };+ for (int c = 0; c < 2; ++c) { dnSteep_[c].set_coefs(steep); dnMid_[c].set_coefs(mid); }+ }++ // ===================================================================================+ // Render+ // ===================================================================================+ // A chunk splits at sequencer events so they land on their exact sample.+ void renderChunk(float* out, int n) {+ syncStructure();+ for (int pos = 0; pos < n;) {+ seqService();+ int m = n - pos;+ const int toEv = seqSamplesToNext();+ if (toEv < m) m = std::max(1, toEv);+ renderSpan(out + pos * 2, m);+ if (!(tPlaying_ && tSpb_ > 1.0)) seqIntBeat_ += m / spb();+ tFrames_ += m;+ pos += m;+ }+ }++ struct Cable { int src, dst; float amt; };+ struct VoiceCtl {+ int os; float invOs; double invFsOs, fsOs, sr;+ float oscOff[kOsc]; int wave[kOsc]; bool sync2, sync4;+ bool lfo24, unison; float uniSpread, drift;+ int fmode; float comp, kbd, velVca, atCut; bool drive;+ float fA, fD, fR, aA, aD, aR, fS, aS;+ float glideC, walkC, invFade, fadeC, cutMax;+ float voiceGain;+ Cable cab[kCables]; int nCab;+ bool patched[consort::kDstN];+ float atten1, atten2;+ };++ void renderSpan(float* out, int n) {+ using namespace consort;+ float P[kNumParams];+ for (int i = 0; i < kNumParams; ++i) P[i] = pn_[i].load(std::memory_order_relaxed);+ const double sr = sampleRate_;++ int os = P[Oversample] < 0.25f ? 1 : P[Oversample] < 0.75f ? 2 : 4;+ if (sr >= 176000.0) os = 1; else if (sr >= 88000.0) os = std::max(1, os / 2);+ if (os != osCur_) { for (int c = 0; c < 2; ++c) { dnSteep_[c].clear_buffers(); dnMid_[c].clear_buffers(); } osCur_ = os; }+ const double fsOs = sr * os;++ // ---- patch cables (per-voice and global destinations) ----+ VoiceCtl c{};+ Cable cabG[kCables]; int nG = 0;+ for (int k = 0; k < kCables; ++k) {+ const int s = jackOf(P[Cable0 + k * 3]), d = jackOf(P[Cable0 + k * 3 + 1]);+ if (s <= 0 || s >= kSrcN || d <= 0 || d >= kDstN) continue;+ const float dp = depthOf(P[Cable0 + k * 3 + 2]);+ const Cable cb{ s, d, dp * std::fabs(dp) * dstScale(d) };+ c.patched[d] = true;+ if (dstIsGlobal(d)) cabG[nG++] = cb; else c.cab[c.nCab++] = cb;+ }+ c.atten1 = depthOf(P[Atten1]); c.atten2 = depthOf(P[Atten2]);++ // ---- global per-sample controls (smoothed ~20 ms) ----+ const float sc = 1.0f - static_cast<float>(std::exp(-1.0 / (0.02 * sr)));+ const float bendR = static_cast<float>(bendRangeOf(P[BendRange]));+ const float tgt[kSm] = {+ (P[Tune] - 0.5f) * 4.0f + (P[Bend] - 0.5f) * 2.0f * bendR, // SmPitch (semis)+ std::log2(20.0f) + std::clamp(P[Cutoff], 0.0f, 1.0f) * 9.96578428f, // SmCut (log2 Hz)+ 4.3f * P[Reso], spacingOctOf(P[Spacing]), envAmtOctOf(P[FEnvAmt]),+ P[Mix1], P[Mix2], P[Mix3], P[Mix4], P[MixNoise], P[MixExt],+ P[Pw], volumeGainOf(P[Volume]) * 2.0f, P[ModWheel], P[Aftertouch],+ lfoCentsOf(P[LfoPitch]) * 0.01f, P[LfoCut] * P[LfoCut] * 4.0f, P[LfoPwm] * 0.45f,+ P[DlyMix], P[DlyFb] };+ if (!smoothInit_) { for (int k = 0; k < kSm; ++k) sm_[k] = tgt[k]; smoothInit_ = true; }++ // LFO+ const int lfoW = std::clamp(static_cast<int>(std::lround(P[LfoWave] * 5.0f)), 0, 5);+ const bool lfoSync = P[LfoSync] > 0.5f && tSpb_ > 1.0;+ double lfoInc = lfoHzOf(P[LfoRate]) / sr;+ if (lfoSync) {+ const double beats = syncBeatsOf(P[LfoRate]);+ lfoInc = 1.0 / (beats * tSpb_);+ if (tFresh_ && tPlaying_) { const double cyc = (tBeat_ + tFrames_ / tSpb_) / beats; lfoPh_ = cyc - std::floor(cyc); }+ }+ tFresh_ = false;+ const Voice& Fv = voices_[focus_];+ const bool atCut = P[AtCut] > 0.5f;++ for (int i = 0; i < n; ++i) {+ for (int k = 0; k < kSm; ++k) sm_[k] += (tgt[k] - sm_[k]) * sc;+ // global patch destinations (sources: global signals now, the focus voice's last sample)+ float gd[4] = { 0, 0, 0, 0 }; // lfo rate, dly time, dly fb, dly mix+ if (nG > 0) {+ float sv[kSrcN];+ fillGlobalSources(sv, lfoVal_, sm_[SmMw], sm_[SmAt], clk_ > 0 ? 1.0f : 0.0f);+ fillVoiceSources(sv, Fv, c, noiseLast_);+ for (int k = 0; k < nG; ++k) {+ const float v = cabG[k].amt * sv[cabG[k].src];+ switch (cabG[k].dst) { case DstLfoRate: gd[0] += v; break; case DstDlyTime: gd[1] += v; break; case DstDlyFb: gd[2] += v; break; default: gd[3] += v; break; }+ }+ }+ // LFO+ const float ph = static_cast<float>(lfoPh_);+ float lfo;+ switch (lfoW) {+ case 0: lfo = std::sin(ph * 6.2831853f); break;+ case 1: lfo = 2.0f * ph - 1.0f; break;+ case 2: lfo = 1.0f - 2.0f * ph; break;+ case 3: lfo = ph < 0.5f ? 1.0f : -1.0f; break;+ case 4: lfo = lfoRnd1_; break;+ default: lfo = lfoRnd0_ + (lfoRnd1_ - lfoRnd0_) * (0.5f - 0.5f * std::cos(ph * 3.14159265f)); break;+ }+ lfoVal_ = lfo;+ lfoPh_ += lfoInc * (gd[0] != 0.0f ? pentad::exp2f(std::clamp(gd[0], -8.0f, 8.0f)) : 1.0f);+ if (lfoPh_ >= 1.0) { lfoPh_ -= std::floor(lfoPh_); lfoRnd0_ = lfoRnd1_; lfoRnd1_ = lfoRng_.bi(); }+ gLfo_[i] = lfo;+ gClk_[i] = clk_ > 0 ? 1.0f : 0.0f; if (clk_ > 0) --clk_;+ gPitch_[i] = sm_[SmPitch];+ gLfoP_[i] = lfo * (sm_[SmLfoP] + sm_[SmMw] * 0.5f);+ gVib_[i] = lfo * sm_[SmMw] * 0.5f;+ gCut_[i] = sm_[SmCut] + lfo * sm_[SmLfoC] + (atCut ? 2.0f * sm_[SmAt] : 0.0f);+ gK_[i] = sm_[SmK]; gSpace_[i] = sm_[SmSpace]; gFenv_[i] = sm_[SmFenv];+ gMix_[0][i] = sm_[SmM1]; gMix_[1][i] = sm_[SmM2]; gMix_[2][i] = sm_[SmM3]; gMix_[3][i] = sm_[SmM4];+ gNzL_[i] = sm_[SmNz]; gExt_[i] = sm_[SmExt];+ gDuty_[i] = dutyOf(sm_[SmPw]) - lfo * sm_[SmLfoPwm] * 0.5f;+ gVol_[i] = sm_[SmVol]; gMw_[i] = sm_[SmMw]; gAt_[i] = sm_[SmAt];+ gDlyT_[i] = gd[1]; gDlyFb_[i] = std::clamp(sm_[SmDlyFb] + gd[2], 0.0f, 1.05f); gDlyMix_[i] = std::clamp(sm_[SmDlyMix] + gd[3], 0.0f, 1.0f);+ }+ // Shared noise at the oversampled rate (white, or Kellet "economy" pink).+ const bool pink = P[NoiseColor] > 0.5f;+ for (int k = 0, m = n * os; k < m; ++k) {+ const float w = noiseRng_.bi();+ if (pink) {+ pk0_ = 0.99765f * pk0_ + w * 0.0990460f;+ pk1_ = 0.96300f * pk1_ + w * 0.2965164f;+ pk2_ = 0.57000f * pk2_ + w * 1.0526913f;+ gNoise_[k] = (pk0_ + pk1_ + pk2_ + w * 0.1848f) * 0.3f;+ } else gNoise_[k] = w;+ }+ noiseLast_ = gNoise_[n * os - 1];++ // ---- voices ----+ const int m = n * os;+ std::fill(osL_, osL_ + m, 0.0f);+ std::fill(osR_, osR_ + m, 0.0f);+ c.os = os; c.invOs = 1.0f / static_cast<float>(os); c.invFsOs = 1.0 / fsOs; c.fsOs = fsOs; c.sr = sr;+ const int oct[kOsc] = { octaveOf(P[O1Oct]), octaveOf(P[O2Oct]), octaveOf(P[O3Oct]), octaveOf(P[O4Oct]) };+ c.oscOff[0] = 12.0f * oct[0];+ c.oscOff[1] = 12.0f * oct[1] + freqSemisOf(P[O2Freq]);+ c.oscOff[2] = 12.0f * oct[2] + freqSemisOf(P[O3Freq]);+ c.oscOff[3] = 12.0f * oct[3] + freqSemisOf(P[O4Freq]);+ c.wave[0] = waveOf(P[O1Wave]); c.wave[1] = waveOf(P[O2Wave]); c.wave[2] = waveOf(P[O3Wave]); c.wave[3] = waveOf(P[O4Wave]);+ c.sync2 = P[O2Sync] > 0.5f; c.sync4 = P[O4Sync] > 0.5f;+ c.lfo24 = P[LfoDest] > 0.5f; c.unison = P[Unison] > 0.5f; c.drift = P[Drift];+ c.uniSpread = (6.0f + 20.0f * c.drift) * 0.01f;+ c.fmode = std::clamp(static_cast<int>(std::lround(P[FiltMode] * 2.0f)), 0, 2);+ c.comp = P[BassComp] > 0.5f ? 1.0f : 0.0f; c.kbd = P[KbdTrk];+ c.velVca = P[VelVca] > 0.5f ? 1.0f : 0.0f; c.drive = P[MixDrive] > 0.5f;+ c.fA = attackSecOf(P[FAttack]) / 1.4663f; c.fD = decaySecOf(P[FDecay]) * 0.25f; c.fR = decaySecOf(P[FRelease]) * 0.25f;+ c.aA = attackSecOf(P[AAttack]) / 1.4663f; c.aD = decaySecOf(P[ADecay]) * 0.25f; c.aR = decaySecOf(P[ARelease]) * 0.25f;+ c.fS = P[FSustain]; c.aS = P[ASustain];+ const float gT = glideSecOf(P[Glide]);+ c.glideC = gT > 0.0f ? 1.0f - static_cast<float>(std::exp(-1.0 / (gT / 3.0 * sr))) : 1.0f;+ c.walkC = 1.0f - static_cast<float>(std::exp(-1.0 / (0.8 * sr)));+ c.invFade = 1.0f / static_cast<float>(fadeLen_);+ c.fadeC = 1.0f - static_cast<float>(std::exp(-1.0 / (0.004 * sr)));+ c.cutMax = static_cast<float>(std::min(fsOs * 0.40, 30000.0));++ const bool poly = structMode() == 3;+ const int S = slotsOf(structMode());+ c.voiceGain = poly ? 0.5f : 1.0f; // a poly voice stacks four oscillators on one note+ int active = 0;+ for (int v = 0; v < (poly ? kMaxVoices : 1); ++v) {+ Voice& V = voices_[v];+ if (!V.active) { V.level = 0.0f; continue; }+ // Unison detune: oscillators sharing a note fan out around it.+ for (int k = 0; k < kOsc; ++k) V.det[k] = 0.0f;+ if (c.unison) {+ for (int k = 0; k < kOsc; ++k) {+ const int key = poly ? 0 : slotNote_[slotOfOsc(k, S)];+ int cnt = 0, idx = 0;+ for (int j = 0; j < kOsc; ++j) {+ const int kj = poly ? 0 : slotNote_[slotOfOsc(j, S)];+ if (kj == key && (poly || V.gT[j] > 0.0f)) { if (j < k) ++idx; ++cnt; }+ }+ if (cnt > 1) V.det[k] = (2.0f * idx / static_cast<float>(cnt - 1) - 1.0f) * c.uniSpread;+ }+ }+ renderVoice(V, n, c);+ if (V.active) ++active;+ }+ if (poly) activeCount_ = active;+ else {+ int own = 0;+ if (voices_[0].active) for (int s = 0; s < S; ++s) if (slotNote_[s] >= 0 && !slotDbl_[s]) ++own;+ activeCount_ = voices_[0].active ? std::max(own, 1) : 0;+ }++ // ---- decimate the oversampled stereo sum ----+ if (os == 1) {+ for (int i = 0; i < n; ++i) { dsL_[i] = osL_[i]; dsR_[i] = osR_[i]; }+ } else if (os == 2) {+ dnSteep_[0].process_block(dsL_, osL_, n); dnSteep_[1].process_block(dsR_, osR_, n);+ } else {+ dnMid_[0].process_block(tmpL_, osL_, n * 2); dnMid_[1].process_block(tmpR_, osR_, n * 2);+ dnSteep_[0].process_block(dsL_, tmpL_, n); dnSteep_[1].process_block(dsR_, tmpR_, n);+ }++ // ---- analog delay + output ----+ processDelay(n, P);+ float pl = 0.0f, prr = 0.0f;+ for (int i = 0; i < n; ++i) {+ float l = dsL_[i] * gVol_[i], r = dsR_[i] * gVol_[i];+ if (!std::isfinite(l) || !std::isfinite(r)) { l = r = 0.0f; }+ out[i * 2] += l; out[i * 2 + 1] += r;+ pl = std::max(pl, std::fabs(l)); prr = std::max(prr, std::fabs(r));+ }+ const float dec = static_cast<float>(std::exp(-n / (0.3 * sr)));+ peakL_ = std::max(pl, peakL_ * dec); peakR_ = std::max(prr, peakR_ * dec);+ }++ // Global patch sources (the sequencer's, LFO, controllers).+ void fillGlobalSources(float* sv, float lfo, float mw, float at, float clk) const {+ using namespace consort;+ sv[SrcNone] = 0.0f; sv[SrcLfo] = lfo;+ sv[SrcSeqPitch] = seqRun_ ? seqPitchV_ : 0.0f; sv[SrcSeqGate] = seqGateV_; sv[SrcClock] = clk;+ sv[SrcAftertouch] = at; sv[SrcModWheel] = mw;+ }+ // Per-voice patch sources (previous sample).+ static void fillVoiceSources(float* sv, const Voice& V, const VoiceCtl& c, float nz) {+ using namespace consort;+ sv[SrcEnv1] = V.fenv; sv[SrcEnv2] = V.aenv;+ sv[SrcOsc1] = V.oPrev[0]; sv[SrcOsc2] = V.oPrev[1]; sv[SrcOsc3] = V.oPrev[2]; sv[SrcOsc4] = V.oPrev[3];+ sv[SrcNoise] = nz; sv[SrcFilt] = V.fPrev;+ sv[SrcKbdPitch] = static_cast<float>(V.note - 60) / 60.0f; sv[SrcKbdGate] = V.gate ? 1.0f : 0.0f; sv[SrcVelocity] = V.vel;+ sv[SrcAtten1] = c.atten1 * V.uIn[0]; sv[SrcAtten2] = c.atten2 * V.uIn[1]; sv[SrcSum] = V.uIn[2];+ }++ void renderVoice(Voice& V, int n, const VoiceCtl& c) {+ using namespace consort;+ const double sr = c.sr;+ const float fA = coefOf(c.fA, sr), fD = coefOf(c.fD, sr), fR = coefOf(c.fR, sr);+ const float aA = coefOf(c.aA, sr), aD = coefOf(c.aD, sr), aR = coefOf(c.aR, sr);+ const float velA = (1.0f - c.velVca * 0.85f * (1.0f - V.vel)) * c.voiceGain;+ const int os = c.os;+ const float kPiF = static_cast<float>(kPi);+ const bool g1p = c.patched[DstGate1], g2p = c.patched[DstGate2];+ const bool filtInP = c.patched[DstFiltIn], vcaInP = c.patched[DstVcaIn], extInP = c.patched[DstExtIn];+ const bool anyCab = c.nCab > 0;+ float* L = osL_; float* R = osR_;+ const float keyOct = (V.note - 60) * (1.0f / 12.0f);++ for (int i = 0; i < n; ++i) {+ // -- stolen-voice fade → hand the voice to its pending note --+ float fadeG = 1.0f;+ if (V.fade > 0) {+ --V.fade;+ fadeG = static_cast<float>(V.fade) * c.invFade;+ if (V.fade == 0) {+ if (V.pendNote >= 0) {+ V.fenv = V.aenv = 0.0f;+ const int pn = V.pendNote; V.pendNote = -1;+ startPoly(static_cast<int>(&V - voices_), pn, V.pendVel, V.pendGlide);+ } else { V.active = false; V.gate = false; V.fst = V.ast = 0; V.fenv = V.aenv = 0.0f; V.level = 0.0f; return; }+ }+ }+ // -- gates: the keyboard, or a patched Gate in (rising edges retrigger while held) --+ if (V.retrig) {+ V.retrig = false;+ if (V.gate) { if (!g1p) V.fst = 1; if (!g2p) V.ast = 1; }+ }+ if (g1p) { const bool g = V.gate && V.gIn1 > 0.25f; if (g && !V.g1s) V.fst = 1; else if (!g && V.g1s && V.fst && V.fst != 3) V.fst = 3; V.g1s = g; }+ if (g2p) { const bool g = V.gate && V.gIn2 > 0.25f; if (g && !V.g2s) V.ast = 1; else if (!g && V.g2s && V.ast && V.ast != 3) V.ast = 3; V.g2s = g; }+ // -- envelopes (RC curves; the attack aims past 1 like the analog charge) --+ switch (V.fst) {+ case 1: V.fenv += (1.3f - V.fenv) * fA; if (V.fenv >= 1.0f) { V.fenv = 1.0f; V.fst = 2; } break;+ case 2: V.fenv += (c.fS - V.fenv) * fD; break;+ case 3: V.fenv -= V.fenv * fR; if (V.fenv < 1e-6f) { V.fenv = 0.0f; V.fst = 0; } break;+ default: break;+ }+ switch (V.ast) {+ case 1: V.aenv += (1.3f - V.aenv) * aA; if (V.aenv >= 1.0f) { V.aenv = 1.0f; V.ast = 2; } break;+ case 2: V.aenv += (c.aS - V.aenv) * aD; break;+ case 3: V.aenv -= V.aenv * aR; if (V.aenv < 3e-5f) { V.aenv = 0.0f; V.ast = 0; } break;+ default: break;+ }+ if (V.ast == 0 && !V.gate && V.fade == 0 && !V.retrig) { // asleep: stop computing this voice+ V.active = false; V.fst = 0; V.level = 0.0f;+ for (int k = 0; k < kOsc; ++k) V.oPrev[k] = 0.0f;+ V.fPrev = V.vPrev = 0.0f;+ return;+ }+ // -- glide (per oscillator) + paraphonic slot fades --+ for (int k = 0; k < kOsc; ++k) {+ const float d = V.tgt[k] - V.pitch[k];+ if (d != 0.0f) {+ if (V.rate[k] < 0.0f) { V.pitch[k] += d * c.glideC; if (std::fabs(d) < 1e-4f) V.pitch[k] = V.tgt[k]; }+ else if (V.rate[k] > 0.0f) { const float st = std::min(std::fabs(d), V.rate[k]); V.pitch[k] += d > 0.0f ? st : -st; }+ else V.pitch[k] = V.tgt[k];+ }+ V.g[k] += (V.gT[k] - V.g[k]) * c.fadeC;+ }+ // -- slow random walk (drift) --+ if (--V.wCount <= 0) {+ for (int k = 0; k <= kOsc; ++k) V.wt[k] = V.rng.bi();+ V.wCount = static_cast<int>(sr * (0.4 + 1.6 * V.rng.uni())) + 1;+ }+ for (int k = 0; k <= kOsc; ++k) V.w[k] += (V.wt[k] - V.w[k]) * c.walkC;++ // -- base-rate control targets --+ float pb[kOsc];+ for (int k = 0; k < kOsc; ++k) {+ const bool lfoOn = !c.lfo24 || k == 1 || k == 3;+ pb[k] = V.pitch[k] + c.oscOff[k] + V.det[k] + gPitch_[i] + (lfoOn ? gLfoP_[i] : gVib_[i])+ + c.drift * (0.15f * V.oOff[k] + 0.1f * V.w[k]);+ }+ const float fe = V.fenv;+ const float cut = gCut_[i] + gFenv_[i] * fe + c.kbd * keyOct + c.drift * (0.25f * V.oCut + 0.1f * V.w[kOsc]);+ const float ca = cut, cb = cut + gSpace_[i];+ const float amp = V.aenv * velA * fadeG;+ const float duty = gDuty_[i];+ if (V.fresh) { for (int k = 0; k < kOsc; ++k) V.pP[k] = pb[k]; V.pCa = ca; V.pCb = cb; V.pAmp = amp; V.pDuty = duty; V.fresh = false; }+ const float k0 = gK_[i];+ const float mix[kOsc] = { gMix_[0][i] * V.g[0], gMix_[1][i] * V.g[1], gMix_[2][i] * V.g[2], gMix_[3][i] * V.g[3] };+ const float nzL = gNzL_[i], extL = gExt_[i];+ const float* nz = gNoise_ + i * os;+ float* lo = L + i * os; float* ro = R + i * os;+ float sv[kSrcN];+ if (anyCab) fillGlobalSources(sv, gLfo_[i], gMw_[i], gAt_[i], gClk_[i]);++ for (int s = 0; s < os; ++s) {+ const float t = static_cast<float>(s + 1) * c.invOs;+ // -- patch (sources from the previous sample) --+ float d[kDstN] = {};+ if (anyCab) {+ fillVoiceSources(sv, V, c, nz[s]);+ for (int q = 0; q < c.nCab; ++q) d[c.cab[q].dst] += c.cab[q].amt * sv[c.cab[q].src];+ V.uIn[0] = d[DstAtten1]; V.uIn[1] = d[DstAtten2]; V.uIn[2] = d[DstSum];+ V.gIn1 = d[DstGate1]; V.gIn2 = d[DstGate2];+ }+ // -- oscillators: 1 → 2 (sync), 3 → 4 (sync) --+ const float du = std::clamp(V.pDuty + (duty - V.pDuty) * t + d[DstPwm], 0.02f, 0.98f);+ float o[kOsc], wrap[kOsc];+ for (int k = 0; k < kOsc; ++k) {+ const float note = V.pP[k] + (pb[k] - V.pP[k]) * t + d[DstPitchAll] + d[DstPitch1 + k];+ const double dt = std::min(440.0 * pentad::exp2f((note - 69.0f) * (1.0f / 12.0f)) * c.invFsOs, 0.45);+ const float sy = (k == 1 && c.sync2) ? wrap[0] : (k == 3 && c.sync4) ? wrap[2] : -1.0f;+ o[k] = oscStep(V.osc[k], dt, c.wave[k], du, sy, wrap[k]);+ }+ // -- mixer (+ noise, EXT: normalled to the VCA output → feedback) --+ const float ext = extInP ? d[DstExtIn] : V.vPrev;+ const float sum = mix[0] * o[0] + mix[1] * o[1] + mix[2] * o[2] + mix[3] * o[3] + nzL * nz[s] + extL * ext;+ float x;+ if (filtInP) x = d[DstFiltIn];+ else x = c.drive ? V.sat.process(sum * 0.45 * 2.4) * (1.0f / 1.3f) : V.sat.process(sum * 0.45 * 0.7) * (1.0f / 0.7f);+ // -- dual ladder --+ const float kk = std::clamp(k0 + d[DstReso] * 4.3f, 0.0f, 4.6f);+ const float cA = V.pCa + (ca - V.pCa) * t + d[DstCut1];+ const float cB = V.pCb + (cb - V.pCb) * t + d[DstCut2];+ const float gA = pentad::tanPrewarp(kPiF * std::clamp(pentad::exp2f(cA), 8.0f, c.cutMax) * static_cast<float>(c.invFsOs));+ const float gB = pentad::tanPrewarp(kPiF * std::clamp(pentad::exp2f(cB), 8.0f, c.cutMax) * static_cast<float>(c.invFsOs));+ float yl, yr;+ if (c.fmode == 0) { yl = yr = V.fb.tick(V.fa.tick(x, gA, kk, c.comp, true), gB, kk, c.comp, false); }+ else { yl = V.fa.tick(x, gA, kk, c.comp, c.fmode == 2); yr = V.fb.tick(x, gB, kk, c.comp, false); }+ // -- VCA (Env 2 × CV; its input normalled to the filter) --+ const float a = (V.pAmp + (amp - V.pAmp) * t) * std::clamp(1.0f + d[DstVcaCv], 0.0f, 3.0f);+ float vl = vcaInP ? d[DstVcaIn] : yl, vr = vcaInP ? d[DstVcaIn] : yr;+ vl = std::clamp(vl, -6.0f, 6.0f) * a; vr = std::clamp(vr, -6.0f, 6.0f) * a;+ vl -= 0.008f * vl * vl * vl; vr -= 0.008f * vr * vr * vr;+ lo[s] += vl; ro[s] += vr;+ for (int k = 0; k < kOsc; ++k) V.oPrev[k] = o[k];+ V.fPrev = 0.5f * (yl + yr);+ V.vPrev = std::clamp(0.5f * (vl + vr) * 2.0f, -2.0f, 2.0f);+ }+ for (int k = 0; k < kOsc; ++k) V.pP[k] = pb[k];+ V.pCa = ca; V.pCb = cb; V.pAmp = amp; V.pDuty = duty;+ V.cutA = ca; V.cutB = cb;+ }+ V.level = V.aenv * velA * (V.fade > 0 ? V.fade * c.invFade : 1.0f);+ }++ // ===================================================================================+ // Bucket-brigade delay (stereo; line rate ≤ 50 kHz, decimated at higher host rates)+ // ===================================================================================+ void setupDelayRate() {+ dlyD_ = sampleRate_ > 100000.0 ? 4 : sampleRate_ > 50000.0 ? 2 : 1;+ dlyRate_ = sampleRate_ / dlyD_;+ dlyPhase_ = 0; dlyAccL_ = dlyAccR_ = 0.0f;+ }+ void clearDelay() {+ if (dlyDirty_ && dlyBuf_) std::memset(dlyBuf_.get(), 0, sizeof(float) * static_cast<size_t>(dlyN_) * 4);+ dlyDirty_ = false;+ dlyW_ = 0;+ for (int c = 0; c < 2; ++c) {+ dlyY_[c] = 0.0f; dlyPrev_[c] = dlyCur_[c] = 0.0f; envIn_[c] = 1e-6f;+ pre_[c].clear(); post_[c].clear();+ dlyTimeCur_[c] = -1.0f;+ }+ setupDelayRate();+ }+ float readGain(int ch, float delay) const { // the compander gain stored beside the signal+ const float* b = dlyBuf_.get() + (2 + ch) * dlyN_;+ const float rp = static_cast<float>(dlyW_) - delay;+ const float fl = std::floor(rp);+ const int i1 = static_cast<int>(fl), mask = dlyN_ - 1;+ const float y1 = b[i1 & mask], y2 = b[(i1 + 1) & mask];+ return y1 + (y2 - y1) * (rp - fl);+ }+ float readLine(int ch, float delay) const {+ const float* b = dlyBuf_.get() + ch * dlyN_;+ const float rp = static_cast<float>(dlyW_) - delay;+ const float fl = std::floor(rp);+ const float f = rp - fl;+ const int i1 = static_cast<int>(fl);+ const int mask = dlyN_ - 1;+ const float y0 = b[(i1 - 1) & mask], y1 = b[i1 & mask], y2 = b[(i1 + 1) & mask], y3 = b[(i1 + 2) & mask];+ const float c1 = 0.5f * (y2 - y0), c2 = y0 - 2.5f * y1 + 2.0f * y2 - 0.5f * y3, c3 = 0.5f * (y3 - y0) + 1.5f * (y1 - y2);+ return ((c3 * f + c2) * f + c1) * f + y1;+ }+ void processDelay(int n, const float* P) {+ if (!dlyBuf_) return;+ const bool digital = P[DlyDigital] > 0.5f, ping = P[DlyPing] > 0.5f;+ const float baseT = dlySecOf(P[DlyTime]), spc = dlySpacingOf(P[DlySpacing]);+ const float maxT = static_cast<float>((dlyN_ - 8) / dlyRate_);+ const float maxTime = std::min(2.0f, maxT);+ const float slew = 1.0f - static_cast<float>(std::exp(-1.0 / (0.12 * dlyRate_)));+ // BBD bandwidth from the virtual clock (8192 stages): longer delays are darker.+ float gPre[2], kq = 1.2f;+ for (int ch = 0; ch < 2; ++ch) {+ const float tsec = dlyTimeCur_[ch] > 0.0f ? dlyTimeCur_[ch] / static_cast<float>(dlyRate_) : baseT;+ const float fclk = 8192.0f / (2.0f * std::max(tsec, 0.005f));+ const float bw = std::clamp(0.42f * fclk, 600.0f, digital ? 16000.0f : 11000.0f);+ gPre[ch] = std::tan(static_cast<float>(kPi) * std::min(bw, static_cast<float>(dlyRate_) * 0.45f) / static_cast<float>(dlyRate_));+ }+ const float envA = 1.0f - static_cast<float>(std::exp(-1.0 / (0.002 * dlyRate_)));+ const float envR = 1.0f - static_cast<float>(std::exp(-1.0 / (0.030 * dlyRate_)));+ const int D = dlyD_;+ for (int i = 0; i < n; ++i) {+ dlyAccL_ += dsL_[i]; dlyAccR_ += dsR_[i];+ if (++dlyPhase_ >= D) {+ dlyPhase_ = 0;+ const float xl = dlyAccL_ / D, xr = dlyAccR_ / D;+ dlyAccL_ = dlyAccR_ = 0.0f;+ const float tl = std::clamp(baseT * pentad::exp2f(std::clamp(gDlyT_[i], -4.0f, 4.0f)), 0.005f, maxTime);+ const float tr = std::clamp(tl + spc, 0.005f, maxTime);+ const float tgt[2] = { tl * static_cast<float>(dlyRate_), tr * static_cast<float>(dlyRate_) };+ const float fb = gDlyFb_[i];+ float y[2];+ for (int ch = 0; ch < 2; ++ch) {+ if (dlyTimeCur_[ch] < 0.0f) dlyTimeCur_[ch] = tgt[ch];+ dlyTimeCur_[ch] += (tgt[ch] - dlyTimeCur_[ch]) * slew;+ const float dl = std::clamp(dlyTimeCur_[ch], 2.0f, static_cast<float>(dlyN_ - 4));+ const float yc = readLine(ch, dl);+ if (digital) y[ch] = yc;+ else y[ch] = post_[ch].tick(yc * readGain(ch, dl), gPre[ch], kq); // expander + reconstruction filter+ dlyY_[ch] = y[ch];+ }+ float inL, inR;+ if (ping) { inL = 0.5f * (xl + xr) + fb * y[1]; inR = fb * y[0]; }+ else { inL = xl + fb * y[0]; inR = xr + fb * y[1]; }+ const float in[2] = { inL, inR };+ float* b = dlyBuf_.get();+ for (int ch = 0; ch < 2; ++ch) {+ float wv = in[ch];+ wv = wv / (1.0f + std::fabs(wv) * 0.35f); // overload+ float gi = 1.0f;+ if (!digital) { // anti-alias filter + 2:1 compressor + hiss (the expander undoes the gain, not the hiss)+ wv = pre_[ch].tick(wv, gPre[ch], kq);+ const float a = std::fabs(wv);+ envIn_[ch] += (a - envIn_[ch]) * (a > envIn_[ch] ? envA : envR);+ const float sq = std::sqrt(std::max(envIn_[ch], 1e-6f));+ wv = wv * (0.25f / sq) + 2.5e-4f * dlyRng_.bi();+ gi = sq * 4.0f;+ }+ if (!std::isfinite(wv)) wv = 0.0f;+ b[ch * dlyN_ + dlyW_] = wv;+ b[(2 + ch) * dlyN_ + dlyW_] = gi;+ if (wv != 0.0f) dlyDirty_ = true;+ }+ dlyW_ = (dlyW_ + 1) & (dlyN_ - 1);+ dlyPrev_[0] = dlyCur_[0]; dlyPrev_[1] = dlyCur_[1];+ dlyCur_[0] = y[0]; dlyCur_[1] = y[1];+ }+ const float fr = D > 1 ? static_cast<float>(dlyPhase_ + 1) / D : 1.0f;+ const float wl = dlyPrev_[0] + (dlyCur_[0] - dlyPrev_[0]) * fr;+ const float wr = dlyPrev_[1] + (dlyCur_[1] - dlyPrev_[1]) * fr;+ const float mx = gDlyMix_[i];+ dsL_[i] += mx * wl; dsR_[i] += mx * wr;+ }+ }++ void publishTelemetry() {+ const int st = structMode();+ tele_[ScMode].store(static_cast<float>(st), std::memory_order_relaxed);+ tele_[ScActive].store(static_cast<float>(activeCount_), std::memory_order_relaxed);+ tele_[ScPeakL].store(peakL_, std::memory_order_relaxed);+ tele_[ScPeakR].store(peakR_, std::memory_order_relaxed);+ tele_[ScCpu].store(static_cast<float>(cpu_), std::memory_order_relaxed);+ tele_[ScOs].store(static_cast<float>(osCur_), std::memory_order_relaxed);+ tele_[ScRate].store(static_cast<float>(sampleRate_), std::memory_order_relaxed);+ tele_[ScStep].store(seqRun_ ? static_cast<float>(curIdx_) : -1.0f, std::memory_order_relaxed);+ tele_[ScBpm].store(tSpb_ > 1.0 ? static_cast<float>(60.0 * sampleRate_ / tSpb_) : 120.0f, std::memory_order_relaxed);+ tele_[ScLfo].store(lfoVal_, std::memory_order_relaxed);+ const Voice& F = voices_[focus_];+ tele_[ScEnv1].store(F.active ? F.fenv : 0.0f, std::memory_order_relaxed);+ tele_[ScEnv2].store(F.active ? F.aenv : 0.0f, std::memory_order_relaxed);+ if (st == 3) { // the four most recent sounding voices+ int idx[kOsc] = { -1, -1, -1, -1 };+ for (int v = 0; v < kMaxVoices; ++v) {+ if (!voices_[v].active) continue;+ for (int j = 0; j < kOsc; ++j) {+ if (idx[j] < 0 || voices_[v].order > voices_[idx[j]].order) {+ for (int q = kOsc - 1; q > j; --q) idx[q] = idx[q - 1];+ idx[j] = v; break;+ }+ }+ }+ for (int j = 0; j < kOsc; ++j) {+ tele_[ScOscNote + j].store(idx[j] >= 0 ? static_cast<float>(voices_[idx[j]].note) : -1.0f, std::memory_order_relaxed);+ tele_[ScOscLvl + j].store(idx[j] >= 0 ? voices_[idx[j]].level : 0.0f, std::memory_order_relaxed);+ }+ } else {+ const Voice& V = voices_[0];+ const int S = slotsOf(st);+ for (int k = 0; k < kOsc; ++k) {+ const int note = slotNote_[slotOfOsc(k, S)];+ const bool on = V.active && note >= 0 && V.gT[k] > 0.0f;+ tele_[ScOscNote + k].store(on ? static_cast<float>(note) : -1.0f, std::memory_order_relaxed);+ tele_[ScOscLvl + k].store(on ? V.aenv * V.g[k] : 0.0f, std::memory_order_relaxed);+ }+ }+ tele_[ScCutA].store(pentad::exp2f(F.cutA), std::memory_order_relaxed);+ tele_[ScCutB].store(pentad::exp2f(F.cutB), std::memory_order_relaxed);+ const float r = static_cast<float>(dlyRate_);+ tele_[ScDlyL].store(dlyTimeCur_[0] > 0.0f ? dlyTimeCur_[0] / r * 1000.0f : 0.0f, std::memory_order_relaxed);+ tele_[ScDlyR].store(dlyTimeCur_[1] > 0.0f ? dlyTimeCur_[1] / r * 1000.0f : 0.0f, std::memory_order_relaxed);+ tele_[ScSeqNote].store(static_cast<float>(seqNote_), std::memory_order_relaxed);+ }++ // ---- state ------------------------------------------------------------------------+ enum Sm { SmPitch = 0, SmCut, SmK, SmSpace, SmFenv, SmM1, SmM2, SmM3, SmM4, SmNz, SmExt,+ SmPw, SmVol, SmMw, SmAt, SmLfoP, SmLfoC, SmLfoPwm, SmDlyMix, SmDlyFb, kSm };++ double sampleRate_ = 44100.0;+ std::atomic<double> pendingRate_{ 44100.0 };+ Voice voices_[kMaxVoices];+ int focus_ = 0;+ // keys (physical), the voice layer's held notes, paraphonic slots+ int keys_[128] = { 0 }; int keyN_ = 0;+ int pHeld_[128] = { 0 }; int pHeldN_ = 0;+ int slotNote_[4] = { -1, -1, -1, -1 }; bool slotDbl_[4] = { false, false, false, false };+ int rr_ = 0; uint64_t orderCtr_ = 0;+ int lastStruct_ = 2, lastSeq_ = 0, fadeLen_ = 176, osCur_ = 2, activeCount_ = 0;+ // sequencer+ int phys_[128] = { 0 }; int physN_ = 0; int lat_[128] = { 0 }; int latN_ = 0;+ bool seqRun_ = false; int seqNote_ = -1, seqBase_ = 60, curIdx_ = -1, curType_ = 3, curSub_ = 0, curPitch_ = 60, arpPos_ = -1, clk_ = 0;+ uint32_t arpCtr_ = 0;+ long long curN_ = LLONG_MIN;+ float seqVel_ = 0.8f, seqPitchV_ = 0.0f, seqGateV_ = 0.0f;+ double seqIntBeat_ = 0.0, nextEvBeat_ = -1e300, offBeat_ = 1e300;+ // transport+ double tBeat_ = 0.0, tSpb_ = 0.0, tPos_ = 0.0, tFrames_ = 0.0; bool tPlaying_ = false, tFresh_ = true;+ // LFO / noise+ double lfoPh_ = 0.0; float lfoRnd0_ = 0.0f, lfoRnd1_ = 0.0f, lfoVal_ = 0.0f, noiseLast_ = 0.0f;+ pentad::Rng noiseRng_, lfoRng_, dlyRng_;+ float pk0_ = 0, pk1_ = 0, pk2_ = 0;+ float sm_[kSm] = {}; bool smoothInit_ = false;+ float gPitch_[kChunk], gLfoP_[kChunk], gVib_[kChunk], gCut_[kChunk], gK_[kChunk], gSpace_[kChunk], gFenv_[kChunk];+ float gMix_[kOsc][kChunk], gNzL_[kChunk], gExt_[kChunk], gDuty_[kChunk], gVol_[kChunk], gMw_[kChunk], gAt_[kChunk];+ float gLfo_[kChunk], gClk_[kChunk], gDlyT_[kChunk], gDlyFb_[kChunk], gDlyMix_[kChunk];+ float gNoise_[kChunk * kMaxOs];+ float osL_[kChunk * kMaxOs], osR_[kChunk * kMaxOs], tmpL_[kChunk * 2], tmpR_[kChunk * 2], dsL_[kChunk], dsR_[kChunk];+ hiir::Downsampler2xFpu<12> dnSteep_[2];+ hiir::Downsampler2xFpu<5> dnMid_[2];+ // delay+ std::unique_ptr<float, FreeDel> dlyBuf_;+ int dlyN_ = kDlyLen, dlyW_ = 0, dlyD_ = 1, dlyPhase_ = 0;+ double dlyRate_ = 44100.0;+ bool dlyDirty_ = false;+ float dlyAccL_ = 0, dlyAccR_ = 0, dlyY_[2] = { 0, 0 }, dlyPrev_[2] = { 0, 0 }, dlyCur_[2] = { 0, 0 };+ float dlyTimeCur_[2] = { -1, -1 }, envIn_[2] = { 1e-6f, 1e-6f };+ consort::SvfLp pre_[2], post_[2];+ float peakL_ = 0, peakR_ = 0;+ double cpu_ = 0.0;+ mutable std::atomic<float> tele_[kScopeN] = {};+ std::atomic<float> pn_[kNumParams];+};++} // namespace notadiff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.hindex b8c566c9..1a21ceea 100644--- a/src/native/nota.engine/src/Engine.h+++ b/src/native/nota.engine/src/Engine.h@@ -508,6 +508,7 @@ public:int32_t addRhythmSynthTrack(); // built-in Nota Rhythm (drum machine, kind 12)int32_t addMonolithTrack(); // built-in Nota Monolith (mono Model-D synth, kind 13)int32_t addPentadTrack(); // built-in Nota Pentad (5-voice Prophet-5 poly, kind 14)+ int32_t addConsortTrack(); // built-in Nota Consort (paraphonic semi-modular, kind 15)void instrumentAction(int32_t trackId, int32_t id, int32_t iarg, float farg); // UI editing channelbool setRhythmVoiceSample(int32_t trackId, int32_t voice, const std::string& path); // Phase 2bool rhythmVoiceInfo(int32_t trackId, int32_t voice, NotaSamplerInfo* out) const; // sample id per voicediff --git a/src/native/nota.engine/src/Engine_Devices.cpp b/src/native/nota.engine/src/Engine_Devices.cppindex 7ae18a59..6f5c5af6 100644--- a/src/native/nota.engine/src/Engine_Devices.cpp+++ b/src/native/nota.engine/src/Engine_Devices.cpp@@ -35,6 +35,7 @@#include "RhythmMachine.h"#include "Monolith.h"#include "Pentad.h"+#include "Consort.h"#include "GrainSynth.h"#include "Arpeggiator.h"#include "MidiChord.h"@@ -224,6 +225,18 @@ int32_t Engine::addPentadTrack() {return id;}+int32_t Engine::addConsortTrack() {+ auto g = std::make_shared<Graph>(*authoring_);+ const int32_t id = nextTrackId_++;+ auto track = std::make_shared<Track>(id, TrackType::Instrument);+ auto inst = std::make_shared<Consort>();+ inst->setSampleRate(transport_.sampleRate());+ track->instrument = inst;+ g->tracks.push_back(track);+ publish(g);+ return id;+}+// UI editing channel for the track's instrument (e.g. Nota Rhythm step patterns). The// instrument object is stable across snapshots, so this mutates it in place (message thread).void Engine::instrumentAction(int32_t trackId, int32_t id, int32_t iarg, float farg) {@@ -465,6 +478,7 @@ std::shared_ptr<Instrument> Engine::cloneInstrument(const Track& src) const {case 12: { auto rh = std::make_shared<RhythmMachine>(); rh->setSampleRate(sr); return rh; }case 13: { auto mo = std::make_shared<Monolith>(); mo->setSampleRate(sr); return mo; }case 14: { auto pe = std::make_shared<Pentad>(); pe->setSampleRate(sr); return pe; }+ case 15: { auto co = std::make_shared<Consort>(); co->setSampleRate(sr); return co; }default: return nullptr;}}@@ -588,6 +602,7 @@ static std::shared_ptr<Instrument> makeBuiltinInstrument(int32_t kind) {case 12: return std::make_shared<RhythmMachine>();case 13: return std::make_shared<Monolith>();case 14: return std::make_shared<Pentad>();+ case 15: return std::make_shared<Consort>();default: return nullptr; // Racks (3/4) / unknown: no simple swap}}diff --git a/src/native/nota.engine/src/RackCore.h b/src/native/nota.engine/src/RackCore.hindex a29526ad..4d89fc12 100644--- a/src/native/nota.engine/src/RackCore.h+++ b/src/native/nota.engine/src/RackCore.h@@ -31,6 +31,7 @@#include "RhythmMachine.h"#include "Monolith.h"#include "Pentad.h"+#include "Consort.h"#include "GrainSynth.h"#include "Sampler.h"#include "SampleBuffer.h"@@ -649,6 +650,7 @@ public:case 12: return std::make_shared<RhythmMachine>();case 13: return std::make_shared<Monolith>();case 14: return std::make_shared<Pentad>();+ case 15: return std::make_shared<Consort>();default: return nullptr; // -1 = no instrument (effect rack); plugins are a follow-up}}diff --git a/src/native/nota.engine/src/nota_engine_track.cpp b/src/native/nota.engine/src/nota_engine_track.cppindex 0227a97b..b0cde791 100644--- a/src/native/nota.engine/src/nota_engine_track.cpp+++ b/src/native/nota.engine/src/nota_engine_track.cpp@@ -134,6 +134,9 @@ int32_t nota_engine_add_monolith_track(NotaEngine* e) {int32_t nota_engine_add_pentad_track(NotaEngine* e) {return e ? ENG(e)->addPentadTrack() : 0;}+int32_t nota_engine_add_consort_track(NotaEngine* e) {+ return e ? ENG(e)->addConsortTrack() : 0;+}void nota_track_instrument_action(NotaEngine* e, int32_t track_id, int32_t id, int32_t iarg, float farg) {if (e) ENG(e)->instrumentAction(track_id, id, iarg, farg);}diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 700507b1..ea1065fc 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -1426,6 +1426,212 @@ Console.WriteLine("-- Nota Pentad --");}}+// ============================ Nota Consort =================================+Console.WriteLine("-- Nota Consort --");+{+ using var ce = new NotaEngine();+ ce.SetBpm(120); ce.SetTimeSignature(4, 4);+ int CI(NotaEngine e, int tr, string id) { for (int i = 0; i < e.PluginParamCount(tr, -1); i++) if (e.PluginParamId(tr, -1, i) == id) return i; return -1; }+ void CS(NotaEngine e, int tr, string id, float v) => e.PluginParamSet(tr, -1, CI(e, tr, id), v);+ void Cable(NotaEngine e, int tr, int slot, int src, int dst, float depth) { CS(e, tr, $"c{slot}src", src / 63f); CS(e, tr, $"c{slot}dst", dst / 63f); CS(e, tr, $"c{slot}amt", 0.5f + depth / 2); }+ float[] Play(Action<NotaEngine, int> setup, NotaNote[] notes, int frames, int block = 512, Action<NotaEngine, int>? each = null)+ {+ using var e = new NotaEngine();+ e.SetBpm(120);+ int tr = e.AddConsortTrack();+ setup(e, tr);+ e.AddMidiClip(tr, 0.0, 32.0);+ e.SetClipNotes(tr, 0, notes);+ var outv = new float[frames * 2]; var tmp = new float[block * 2];+ e.Seek(0); e.Play();+ for (int done = 0; done < frames;) { int m = Math.Min(block, frames - done); e.RenderOffline(tmp, m); Array.Copy(tmp, 0, outv, done * 2, m * 2); done += m; each?.Invoke(e, tr); }+ e.StopTransport();+ return outv;+ }+ static float RmsRange(float[] b, int from, int to) { double sum = 0; for (int i = from * 2; i < to * 2; i++) sum += b[i] * (double)b[i]; return (float)Math.Sqrt(sum / Math.Max(1, (to - from) * 2)); }+ static double MaxDiff(float[] a, float[] b) { double d = 0; for (int i = 0; i < Math.Min(a.Length, b.Length); i++) d = Math.Max(d, Math.Abs(a[i] - b[i])); return d; }++ int t = ce.AddConsortTrack();+ Check(t > 0, "AddConsortTrack returns a track");+ Check(ce.TrackInstrumentKind(t) == 15, $"instrument kind is 15 (got {ce.TrackInstrumentKind(t)})");+ Check(ce.DeviceName(t, -1) == "Nota Consort", $"instrument is Nota Consort (got '{ce.DeviceName(t, -1)}')");+ int pc = ce.PluginParamCount(t, -1);+ Check(pc == 145, $"Nota Consort exposes 145 params (got {pc})");+ var cids = new HashSet<string>();+ bool cnames = true;+ for (int i = 0; i < pc; i++) { cids.Add(ce.PluginParamId(t, -1, i)); if (ce.PluginParamName(t, -1, i).Length == 0) cnames = false; }+ Check(cids.Count == pc && !cids.Contains("") && cnames, "consort param ids are unique + non-empty, every param has a name");++ // State (incl. a patch cable and a step) round-trips to another track; duplicate clones it.+ CS(ce, t, "cutoff", 0.77f); Cable(ce, t, 3, 1, 10, 0.4f); CS(ce, t, "sp5", 0.9f);+ var cstate = ce.GetPluginState(t, -1);+ int t2c = ce.AddConsortTrack();+ ce.SetPluginState(t2c, -1, cstate);+ Check(Math.Abs(ce.PluginParamGet(t2c, -1, CI(ce, t2c, "cutoff")) - 0.77f) < 1e-4 && Math.Abs(ce.PluginParamGet(t2c, -1, CI(ce, t2c, "c3dst")) - 10 / 63f) < 1e-4+ && Math.Abs(ce.PluginParamGet(t2c, -1, CI(ce, t2c, "sp5")) - 0.9f) < 1e-4, "consort state restores params, cables and steps on another track");+ int t3c = ce.DuplicateTrack(t);+ Check(t3c > 0 && Math.Abs(ce.PluginParamGet(t3c, -1, CI(ce, t3c, "c3amt")) - 0.7f) < 1e-4, "duplicate track clones the consort patch");++ // Every voice structure sounds a 4-note chord: MONO 1, DUO 2, PARA 4, true poly 4 notes.+ var cchord = new[] { new NotaNote(48, 0.0, 2.0, 0.9f), new NotaNote(55, 0.0, 2.0, 0.9f), new NotaNote(60, 0.0, 2.0, 0.9f), new NotaNote(64, 0.0, 2.0, 0.9f) };+ foreach (var (name, mode, poly, want) in new[] { ("MONO", 0f, 0f, 1), ("DUO", 0.5f, 0f, 2), ("PARA", 1f, 0f, 4), ("POLY", 1f, 1f, 4) })+ {+ int voices = -1;+ var b = Play((e, tr) => { CS(e, tr, "voicemode", mode); CS(e, tr, "truepoly", poly); }, cchord, 8192, 512, (e, tr) => voices = e.InstrumentVoiceCount(tr));+ Check(b.All(float.IsFinite) && Rms(b, 8192) > 0.01f && voices == want, $"Nota Consort {name}: a chord is audible + finite, {want} note(s) sound (RMS {Rms(b, 8192):F3}, {voices})");+ }+ // Paraphony: the notes land on the oscillators (scope telemetry).+ {+ using var e = new NotaEngine(); e.SetBpm(120);+ int tr = e.AddConsortTrack(); CS(e, tr, "unison", 0f);+ e.AddMidiClip(tr, 0, 4); e.SetClipNotes(tr, 0, new[] { new NotaNote(48, 0, 2, 0.9f), new NotaNote(55, 0, 2, 0.9f), new NotaNote(62, 0, 2, 0.9f) });+ var tmp = new float[4096 * 2]; e.Seek(0); e.Play(); e.RenderOffline(tmp, 4096);+ var sc = new float[32]; e.InstrumentScope(tr, sc); e.StopTransport();+ var oscNotes = sc.Skip(12).Take(4).Select(v => (int)v).OrderBy(v => v).ToArray();+ Check(oscNotes.SequenceEqual(new[] { -1, 48, 55, 62 }), $"Nota Consort PARA assigns 3 held notes to 3 oscillators, the 4th idle without unison (got {string.Join(",", oscNotes)})");+ }+ // Filter modes and waves render finite + audible at high resonance.+ foreach (var fm in new[] { 0f, 0.5f, 1f })+ {+ var b = Play((e, tr) => { CS(e, tr, "filtmode", fm); CS(e, tr, "reso", 0.95f); }, new[] { new NotaNote(48, 0, 2, 0.9f) }, 22050);+ Check(b.All(float.IsFinite) && Rms(b, 22050) > 0.003f, $"Nota Consort filter mode {fm:0.0} audible + finite at resonance 95 % (RMS {Rms(b, 22050):F4})");+ }++ // Sequencer: 1/16 at 120 BPM = 8 steps a second, locked to the host grid; ARP walks the chord.+ {+ var steps = new HashSet<int>(); var seqNotes = new HashSet<int>();+ Play((e, tr) => { CS(e, tr, "seqmode", 0.5f); }, new[] { new NotaNote(60, 0, 8, 0.9f) }, 44100 * 2, 256,+ (e, tr) => { var sc = new float[32]; e.InstrumentScope(tr, sc); steps.Add((int)sc[7]); if (sc[24] >= 0) seqNotes.Add((int)sc[24]); });+ Check(steps.Contains(0) && steps.Contains(15) && steps.Count >= 16, $"Nota Consort SEQ runs all 16 steps in 2 s at 1/16, 120 BPM (saw {steps.Count} distinct)");+ Check(seqNotes.SetEquals(new[] { 60, 63, 65, 67, 70, 72 }), $"Nota Consort SEQ transposes the default pattern from the held key (got {string.Join(",", seqNotes.OrderBy(x => x))})");+ var arpNotes = new HashSet<int>();+ Play((e, tr) => { CS(e, tr, "seqmode", 1f); CS(e, tr, "arpoct", 0.5f); }, new[] { new NotaNote(60, 0, 8, 0.9f), new NotaNote(64, 0, 8, 0.9f), new NotaNote(67, 0, 8, 0.9f) }, 44100 * 2, 256,+ (e, tr) => { var sc = new float[32]; e.InstrumentScope(tr, sc); if (sc[24] >= 0) arpNotes.Add((int)sc[24]); });+ Check(arpNotes.SetEquals(new[] { 60, 64, 67, 72, 76, 79 }), $"Nota Consort ARP plays the chord over 2 octaves (got {string.Join(",", arpNotes.OrderBy(x => x))})");+ // rests are silent: an all-rest pattern plays nothing+ var rest = Play((e, tr) => { CS(e, tr, "seqmode", 0.5f); for (int s2 = 1; s2 <= 16; s2++) CS(e, tr, $"st{s2}", 1f); }, new[] { new NotaNote(60, 0, 8, 0.9f) }, 44100);+ Check(Rms(rest, 44100) < 1e-4f, $"Nota Consort SEQ: an all-rest pattern is silent (RMS {Rms(rest, 44100):G3})");+ }++ // BBD delay: echoes after the note, each repeat ~fb lower (−6 dB at 50 %), BBD and digital alike.+ foreach (var dig in new[] { 0f, 1f })+ {+ var b = Play((e, tr) => { CS(e, tr, "dlymix", 1f); CS(e, tr, "dlyfb", 0.5f); CS(e, tr, "dlyping", 0f); CS(e, tr, "dlyspacing", 0.5f); CS(e, tr, "dlydigital", dig);+ CS(e, tr, "adecay", 0.05f); CS(e, tr, "asustain", 0f); CS(e, tr, "arelease", 0.02f); },+ new[] { new NotaNote(72, 0, 0.05, 1f) }, 44100 * 2);+ double T = 0.02 * Math.Pow(75, 0.62);+ float Pk(int k) { int c0 = (int)(k * T * 44100), c1 = c0 + 4000; float pk = 0; for (int i = c0; i < c1; i++) pk = Math.Max(pk, Math.Abs(b[i * 2])); return pk; }+ double r = 20 * Math.Log10(Pk(3) / Pk(2));+ Check(Pk(1) > 0.01f && r < -4.5 && r > -8.5, $"Nota Consort {(dig > 0 ? "digital" : "BBD")} delay repeats decay ~6 dB at 50 % feedback ({r:0.0} dB)");+ }++ // Patch bay: a cable changes the sound; Noise → Filt in breaks the mixer normal; LFO → Gate 2 gates the VCA.+ {+ var note = new[] { new NotaNote(57, 0, 2, 0.9f) };+ var dry = Play((e, tr) => { }, note, 22050);+ var vib = Play((e, tr) => Cable(e, tr, 1, 1, 4, 0.5f), note, 22050);+ Check(MaxDiff(dry, vib) > 0.05, "Nota Consort: LFO → Osc pitch changes the render");+ var silentMix = Play((e, tr) => { foreach (var m in new[] { "mix1", "mix2", "mix3", "mix4" }) CS(e, tr, m, 0f); }, note, 22050);+ var noiseIn = Play((e, tr) => { foreach (var m in new[] { "mix1", "mix2", "mix3", "mix4" }) CS(e, tr, m, 0f); Cable(e, tr, 1, 8, 13, 1f); CS(e, tr, "cutoff", 0.8f); }, note, 22050);+ Check(Rms(silentMix, 22050) < 1e-3f && Rms(noiseIn, 22050) > 0.01f, $"Nota Consort: Noise → Filt in replaces the (silent) mixer normal (RMS {Rms(silentMix, 22050):G2} → {Rms(noiseIn, 22050):F3})");+ var gated = Play((e, tr) => { CS(e, tr, "lfowave", 0.6f); CS(e, tr, "lforate", 0.577f); CS(e, tr, "arelease", 0.05f); CS(e, tr, "aattack", 0f); Cable(e, tr, 1, 1, 3, 1f); }, note, 44100);+ float lo = 1, hi = 0; for (int w = 2; w < 20; w++) { float r = RmsRange(gated, w * 2205, (w + 1) * 2205); lo = Math.Min(lo, r); hi = Math.Max(hi, r); }+ Check(hi > 0.01f && lo < hi * 0.2f, $"Nota Consort: LFO square → Gate 2 in chops the amp envelope (min {lo:F4} / max {hi:F3})");+ var extreme = Play((e, tr) =>+ {+ for (int k = 1; k <= 12; k++) Cable(e, tr, k, 1 + (k * 7) % 20, 1 + (k * 5) % 22, k % 2 == 0 ? 1f : -1f);+ foreach (var id in new[] { "reso", "mixnoise", "mixext", "mixdrive", "fenvamt", "lfocut", "lfopwm", "dlyfb", "dlymix", "truepoly", "oversample", "unison", "o2sync", "o4sync" }) CS(e, tr, id, 1f);+ }, new[] { new NotaNote(24, 0, 4, 1f), new NotaNote(108, 0, 4, 1f), new NotaNote(60, 1, 4, 1f) }, 44100 * 3);+ Check(extreme.All(float.IsFinite), "Nota Consort stays finite with all 12 cables at ±100 %, resonance, feedback and drive at max");+ }++ // Determinism (Freeze: offline == realtime): bit-identical at any block size.+ {+ Action<NotaEngine, int> st = (e, tr) => { CS(e, tr, "drift", 0.8f); CS(e, tr, "mixnoise", 0.3f); CS(e, tr, "dlymix", 0.4f); CS(e, tr, "seqmode", 1f); CS(e, tr, "seqorder", 1f); CS(e, tr, "lfowave", 0.8f); Cable(e, tr, 1, 1, 10, 0.6f); Cable(e, tr, 2, 6, 5, 0.2f); };+ NotaNote[] ph = { new(60, 0, 1.5, 0.8f), new(64, 0.25, 1, 0.7f), new(67, 0.5, 1.5, 0.9f) };+ var a = Play(st, ph, 44100, 4096); var b2 = Play(st, ph, 44100, 128); var c = Play(st, ph, 44100, 777);+ Check(Rms(a, 44100) > 0.001f && MaxDiff(a, b2) == 0 && MaxDiff(a, c) == 0, $"Nota Consort null test: bit-identical at blocks 4096/128/777 (maxdiff {Math.Max(MaxDiff(a, b2), MaxDiff(a, c)):G3})");+ }+ // Freeze captures exactly what the live chain plays.+ {+ using var fe = new NotaEngine(); fe.SetBpm(120);+ int ft = fe.AddConsortTrack();+ CS(fe, ft, "drift", 0.7f); CS(fe, ft, "dlymix", 0.3f); CS(fe, ft, "seqmode", 0.5f);+ fe.AddMidiClip(ft, 0.0, 4.0);+ fe.SetClipNotes(ft, 0, new[] { new NotaNote(57, 0.0, 3.0, 0.9f) });+ const int N = 8192 * 4;+ fe.Seek(0); fe.Play(); var live = new float[N * 2]; fe.RenderOffline(live, N); fe.StopTransport();+ fe.Stop(); fe.SetLoop(false, 0, 0); fe.SetMetronome(false); fe.StopTransport();+ long total = fe.BeginFreeze(ft, 4.0);+ fe.StopTransport(); fe.Seek(0); fe.Play();+ var chunk = new float[4096 * 2];+ for (long rem = total; rem > 0;) { int m = (int)Math.Min(4096, rem); fe.RenderOffline(chunk, m); rem -= m; }+ fe.StopTransport(); fe.EndFreeze(ft);+ fe.Seek(0); fe.Play(); var frozen = new float[N * 2]; fe.RenderOffline(frozen, N); fe.StopTransport();+ double md = MaxDiff(live, frozen);+ Check(fe.IsTrackFrozen(ft) && Rms(live, N) > 1e-3f && md < 1e-5, $"Nota Consort freeze == live render (maxdiff {md:G3})");+ }+ // Automation drives the cutoff and a cable's depth.+ {+ int ta = ce.AddConsortTrack();+ foreach (var id in new[] { "cutoff", "c1amt" })+ {+ int fi = CI(ce, ta, id);+ ce.PluginParamSet(ta, -1, fi, 0.1f);+ int lane = ce.AddPluginAutomationLane(ta, -1, id);+ ce.SetAutomationPoints(ta, lane, new[] { new AutomationPoint(0.0, 0.1f, 0f), new AutomationPoint(2.0, 0.9f, 0f) });+ var abuf = new float[4096 * 2];+ ce.Seek(1.99); ce.Play(); ce.RenderOffline(abuf, 4096); ce.StopTransport();+ Check(lane >= 0 && ce.PluginParamGet(ta, -1, fi) > 0.7f, $"automation drives Consort {id} ({ce.PluginParamGet(ta, -1, fi):F2})");+ }+ }+ // Stress: 16-voice true poly, ×4 oversampling, resonance and four cables in real time.+ {+ using var se = new NotaEngine(); se.SetBpm(120);+ int ta = se.AddConsortTrack();+ CS(se, ta, "truepoly", 1f); CS(se, ta, "oversample", 1f); CS(se, ta, "reso", 1f); CS(se, ta, "dlymix", 0.5f);+ for (int k = 1; k <= 4; k++) Cable(se, ta, k, k, 3 + k, 0.4f);+ se.AddMidiClip(ta, 0, 16);+ var ns = new NotaNote[16]; for (int i = 0; i < 16; i++) ns[i] = new NotaNote(36 + i * 3, 0, 16, 1f);+ se.SetClipNotes(ta, 0, ns);+ var blk = new float[128 * 2]; se.Seek(0); se.Play();+ for (int i = 0; i < 50; i++) se.RenderOffline(blk, 128);+ var sw = System.Diagnostics.Stopwatch.StartNew(); const int blocks = 1000;+ for (int i = 0; i < blocks; i++) se.RenderOffline(blk, 128);+ sw.Stop();+ double budget = 128 / 44.1, avg = sw.Elapsed.TotalMilliseconds / blocks;+ Check(se.InstrumentVoiceCount(ta) == 16 && avg < budget * 0.5, $"Nota Consort stress: 16 voices ×4 OS avg {avg:0.000} ms per 128-frame block (budget {budget:0.00} ms)");+ se.StopTransport();+ }+ // Factory presets: every named param is a real Consort id, each applies in place and sounds.+ {+ var cat = new FactoryPresetCatalog();+ var mine = cat.All().Where(p => p.IsInstrument && p.BuiltinKind == 15).ToList();+ Check(mine.Count == 28, $"Nota Consort ships 28 factory presets (got {mine.Count})");+ var bad = mine.SelectMany(p => cat.Document(p.Id)!.NamedParams!.Keys.Where(k => !cids.Contains(k)).Select(k => $"{p.DisplayName}:{k}")).ToList();+ Check(bad.Count == 0, $"every Consort preset param id exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");+ int ta = ce.AddConsortTrack();+ int fails = mine.Count(p => cat.ApplyInPlace(ce, p.Id, ta, -1).Length != 0);+ Check(fails == 0, $"every Consort preset applies in place ({fails} failed)");+ var quiet = new List<string>();+ foreach (var p in mine)+ {+ var b = Play((e, tr) => cat.ApplyInPlace(e, p.Id, tr, -1), new[] { new NotaNote(48, 0, 2, 0.9f), new NotaNote(55, 0, 2, 0.9f), new NotaNote(60, 0, 2, 0.9f) }, 44100);+ float r = Rms(b, 44100), pk = b.Max(Math.Abs);+ if (!b.All(float.IsFinite) || r < 0.005f || pk > 2f) quiet.Add($"{p.DisplayName} ({r:F3}/{pk:F2})");+ }+ Check(quiet.Count == 0, $"every Consort preset sounds a held chord, finite and not clipping hard{(quiet.Count > 0 ? " — " + string.Join(", ", quiet) : "")}");+ }+ // MCP: add by kind 15.+ {+ var mcp = new Nota.Mcp.Tools.InstrumentTools(ce, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());+ int mt = mcp.AddInstrumentTrack(15).Result;+ Check(mt > 0 && ce.TrackInstrumentKind(mt) == 15, "MCP add_instrument_track(15) adds a Nota Consort");+ Check(mcp.ListInstrumentKinds().Any(k => k.Kind == 15 && k.Name == "Nota Consort"), "MCP list_instrument_kinds includes Nota Consort");+ Check(mcp.SetInstrumentParamById(mt, "c1amt", 0.3f).Result && Math.Abs(ce.PluginParamGet(mt, -1, CI(ce, mt, "c1amt")) - 0.3f) < 1e-4, "MCP set_instrument_param_by_id sets a Consort cable depth");+ }+}+static void Fft(double[] re, double[] im){int n = re.Length;