Skip to content

armgit / nota

Public Imported from GitHub
0

Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.

Redesign of Rhythm

Egor Khindikaynenfa561a169c41
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a0864ce8..1e9b88f1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,38 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Added
+- **Nota Rhythm's editor is now the almanac's card, with the new mockup's features.** The
+ drum machine moves from its 900 px layout onto the 700 × 260 frame: the **kit** on the
+ left, the selected **voice** in the middle, a fixed 186 px **Perform** rail, a full-width
+ **step** strip and a status line.
+ - **Kit** — the eight voices with their hue, SYN / SMP. Clicking a voice selects it and
+ plays it; drop a file on it to load a sample; right-click to load, switch source or
+ clear its steps.
+ - **Voice · Synth** — the **hit** contour (amp over the pitch drop, the pitch and decay
+ times in the corner) is a control: drag across for Decay, up / down for Tune. Then Tune,
+ Decay, Punch, Tone, Drive, Level.
+ - **Voice · Sample** — new per-voice **Start**, **Length** and **Reverse**: the file draws
+ in the voice's hue with the played region between two brass lines you drag, and the play
+ position in teal. Load file… sits in the header; a fresh sample plays at its own pitch.
+ - **Perform** — Swing, Human, Accent as teal sliders, **Master**, and new **Glue**: a bus
+ compressor on the whole kit (0 = off) whose makeup never makes a hit louder than it came
+ in. An output meter beside them.
+ - **Step** — brass steps with their number, bright brass accents and new **quiet steps**
+ (a brass outline; ⌥-click), a teal velocity lane, banks A–D in teal. Drag across to
+ paint, drag up / down or scroll for velocity; right-click for accent / quiet / velocity,
+ fills (beats, 8ths, 16ths, off-beats), shift left / right, reverse and clear. Right-click
+ a bank to copy it to another or clear it.
+ - The status line reads the voice and its steps ("steps 1 · 5 · 9 accent · 13"); the
+ header counts the sounding voices. Edits made over MCP show up on the card at once.
+- **MCP: Rhythm tools grow.** `get_rhythm` now returns each voice's sound (with tune and
+ decay in units), its sample, the row as text, the groove, the playing step, a summary and
+ a parameter guide. New: `set_rhythm_pattern` (rows as text — `x` on, `X` accent, `o`
+ quiet), `set_rhythm_voice`, `set_rhythm_perform`, `copy_rhythm_bank`,
+ `clear_rhythm_voice`, `select_rhythm_voice` and `audition_rhythm_voice`.
+- **Nota Rhythm ships 29 factory kits** (was 6) — classic machines, house / techno / electro,
+ hip-hop and breaks, world and brushes, glitch and ambient textures. A kit sets the sound
+ and keeps the pattern and each voice's sample region; your own kits can now be saved as
+ presets too.
- **Nota Sampler's editor is now the almanac's card, with the new mockup's features.** The card
moves onto the 700 × 260 frame the other instruments use: a **Sample** / **Pitch** / **Env** /
**Filter** tab panel with a one-line reading beside the tabs, a fixed 186 px rail and a
@@ -189,6 +221,9 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
level, the effective attack and release, look-ahead latency and how often it kicked in.
### Changed
+- **Nota Rhythm's automation menu is grouped** by voice (Kick › Tune, Closed Hat › Decay),
+ **Perform** (Swing, Humanize, Accent) and **Master** (Volume, Glue). Ids are unchanged, so
+ existing lanes keep working; projects saved before keep their kits and patterns.
- **Nota Sampler's automation menu is grouped.** Its parameters list under **Sample**, **Loop**,
**Pitch**, **Env**, **Filter**, **Voice** and **Out** (e.g. Filter › Cutoff, Loop ›
Crossfade); the ids are unchanged, so existing lanes and projects keep working. The six new
diff --git a/DESIGN.md b/DESIGN.md
index 64d4625e..a342a728 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -368,8 +368,9 @@ Every built-in device is a **700 × 260** card (`DeviceCardKit.CardH`, width fro
(teal for LFOs and envelopes) on the arc; end-of-chain trim fills with Border strong.
- A bypassed card keeps its layout and turns to the disabled look via `Inactive`.
-Width exceptions, by decision: **Rhythm 900, Bass 1060, Physical 720** (squeezing
-them would be a redesign) and the host-plugin / parameter-list stubs (230, 190).
+Width exceptions, by decision: **Bass 1060, Physical 720** (squeezing them would be a
+redesign) and the host-plugin / parameter-list stubs (230, 190). Rhythm moved onto the
+700 frame with its redesign.
## Shell
@@ -428,7 +429,7 @@ Decisions taken while aligning the app, kept on purpose:
Amp Model (7) and Cabinet (5), Compressor Character (5), Vintage Character (6), Delay
Division (8), Arp Rate (8) and Order (8), Aurora Warp (5) and Filter (5), Bass LFO wave (5),
Monolith Glide range (6), Pendulum Division (5) and Wave (5).
-- **Wide instruments** — Rhythm, Bass, Physical (see § Device cards).
+- **Wide instruments** — Bass, Physical (see § Device cards).
- **Preset picker in the device header.** The almanac allows only name, badge and bypass
there; switching presets is frequent enough to stay one click away.
- **Zoom 28 px per beat** by default, not a 16 px bar; the ruler labels every bar once a bar
@@ -438,7 +439,7 @@ Decisions taken while aligning the app, kept on purpose:
Auto Shift note, Level value.
- **Play turns green in Session** (`tp-play.session`) while clips run.
- **Data hues close to a chroma** — Strata layer `#C99C55`, tag swatch `#C8A24B`, Random
- `#D0603F`, Rhythm dot `#7FC9C6` — are data colours, not accents.
+ `#D0603F`, the Rhythm kit dots (`#C77F55` Kick … `#5AA0B8` Tom) — are data colours, not accents.
## Known drift
diff --git a/FEATURES.md b/FEATURES.md
index b2537e65..6d9414bd 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -312,8 +312,12 @@ and user presets, automation, persistence and cloning.
(Age/Motion/Filter/Env/Space), glide, tune and gain. 25 factory presets.
- **Nota Rhythm** — drum machine: 8 voices (analog and FM kick, noise snare, metallic
hats, clap, rim, tom, perc), a 16-step sequencer (locked to the transport), 4 pattern
- banks (A–D), accents, per-step velocity, Swing/Humanize, and a per-voice **Sample** mode
- (load your own one-shot). Six factory kits (808/909/Trap/House/Lo-Fi/Techno).
+ banks (A–D, copy / clear), accents, quiet steps, per-step velocity, Swing/Humanize, a
+ **Glue** bus compressor, and a per-voice **Sample** mode (load your own one-shot, with a
+ Start / Length region and Reverse). The 700 × 260 card: kit list, an interactive hit
+ contour or sample region, Perform rail with an output meter, a full-width step strip with
+ a velocity lane. 29 factory kits; MCP `get_rhythm`, `set_rhythm_pattern` (text rows),
+ `set_rhythm_voice`, `set_rhythm_perform`, `copy_rhythm_bank`, `audition_rhythm_voice`.
- **Nota Pentad** — 5-voice analog poly in the Prophet-5 mould: Osc A (saw + pulse, hard
sync) and Osc B (saw + triangle + pulse, Lo-Freq, keyboard off), noise, a 24 dB/oct
resonant filter that self-oscillates and tracks the keyboard, two analog-curve ADSRs,
diff --git a/src/managed/Nota.App/Controls/RhythmHitViz.cs b/src/managed/Nota.App/Controls/RhythmHitViz.cs
deleted file mode 100644
index d8042594..00000000
--- a/src/managed/Nota.App/Controls/RhythmHitViz.cs
+++ /dev/null
@@ -1,81 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
-//
-// Nota Rhythm — the "HIT" preview in the voice engine panel: an amp-decay envelope with a
-// decaying oscillation whose pitch drops at the attack, drawn from the selected voice's
-// Decay / Tune / Punch. Flashes brass when the voice triggers (fed from the scope). Purely
-// a visual; the card sets the four values each tick.
-
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Media;
-
-namespace Nota.App;
-
-internal sealed class RhythmHitViz : Control
-{
- private double _decay = 0.5, _tune = 0.4, _punch = 0.5, _flash;
-
- private static readonly IBrush EnvBrush = NotaPalette.AccentDim;
- private static Color Osc => NotaPalette.AccentBright.Color;
- private static readonly IPen ClickPen = new Pen(NotaPalette.Wash(NotaPalette.TealBright, 0x80), 1);
-
- public void Set(double decay, double tune, double punch, double flash)
- {
- _decay = decay; _tune = tune; _punch = punch; _flash = flash;
- InvalidateVisual();
- }
-
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height;
- if (w < 4 || h < 4) return;
- double mid = h * 0.5;
- // How far across the amp decay reaches (longer Decay = wider tail).
- double span = w * (0.25 + _decay * 0.72);
- double k = 4.5 / span; // exp falloff so the tail lands near `span`
-
- // amp-decay envelope (upper half mirror).
- var env = new StreamGeometry();
- using (var g = env.Open())
- {
- g.BeginFigure(new Point(2, mid), false);
- for (double x = 2; x <= w; x += 3)
- {
- double e = System.Math.Exp(-k * (x - 2));
- g.LineTo(new Point(x, mid - e * (mid - 3)));
- }
- }
- ctx.DrawGeometry(null, new Pen(EnvBrush, 1), env);
-
- // decaying oscillation with a pitch drop at the attack (kick-like).
- double baseCyc = 2.0 + _tune * 10.0; // visible cycles across the span
- var osc = new StreamGeometry();
- using (var g = osc.Open())
- {
- g.BeginFigure(new Point(2, mid), false);
- double phase = 0;
- double prevX = 2;
- for (double x = 2; x <= w; x += 1.5)
- {
- double t = (x - 2) / System.Math.Max(1, span);
- double e = System.Math.Exp(-k * (x - 2));
- double freq = baseCyc * (1.0 + 2.5 * System.Math.Exp(-6.0 * t)); // drop
- phase += freq * (x - prevX) / System.Math.Max(1, span) * System.Math.PI * 2 * 0.15;
- prevX = x;
- double y = mid - System.Math.Sin(phase) * e * (mid - 4);
- g.LineTo(new Point(x, y));
- }
- }
- var oscCol = Osc;
- if (_flash > 0.01) oscCol = Color.FromArgb(255,
- (byte)System.Math.Min(255, Osc.R + _flash * (255 - Osc.R)),
- (byte)System.Math.Min(255, Osc.G + _flash * (255 - Osc.G)),
- (byte)System.Math.Min(255, Osc.B + _flash * (255 - Osc.B)));
- ctx.DrawGeometry(null, new Pen(new SolidColorBrush(oscCol), 1.5), osc);
-
- // attack click marker.
- double cx = 2 + _punch * 6;
- ctx.DrawLine(ClickPen, new Point(cx, 3), new Point(cx, h - 3));
- }
-}
diff --git a/src/managed/Nota.App/Controls/RhythmViews.cs b/src/managed/Nota.App/Controls/RhythmViews.cs
new file mode 100644
index 00000000..dd6daa91
--- /dev/null
+++ b/src/managed/Nota.App/Controls/RhythmViews.cs
@@ -0,0 +1,412 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Rhythm's windows (the almanac's Rhythm card):
+//
+// RhythmHitView the selected synth voice's hit: the amp contour (brass) over the pitch
+// drop (deep brass) or the attack click, the trigger as a teal tick; the
+// corner reads the pitch time · the decay. Drag it: across = Decay,
+// up / down = Tune. Lights when the voice fires.
+// RhythmSampleView the selected sample voice: the file as bars in the voice's hue, the
+// played region between a brass Start line and a dashed brass End line
+// (drag either), the part outside dimmed, the play position in teal.
+// RhythmStepStrip the sixteen steps of the selected voice and, under them, the velocity
+// lane. Click toggles, shift-click accents, alt-click makes a quiet step;
+// drag across paints, drag up / down (or the wheel) sets the velocity;
+// right-click asks the card for the step menu.
+
+using System;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+using Nota.Application;
+
+namespace Nota.App;
+
+internal static class RhythmInk
+{
+ public static FormattedText Mono(string t, IBrush ink, double size = 7)
+ => new(t, NotaNum.Culture, FlowDirection.LeftToRight, NotaFonts.Mono, size, ink);
+
+ public static void TopRight(DrawingContext ctx, double w, string t, IBrush ink)
+ {
+ var ft = Mono(t, ink);
+ ctx.DrawText(ft, new Point(w - 5 - ft.Width, 3));
+ }
+
+ public static void BottomRight(DrawingContext ctx, double w, double h, string t)
+ {
+ var ft = Mono(t, NotaPalette.TextAxis);
+ ctx.DrawText(ft, new Point(w - 5 - ft.Width, h - 2 - ft.Height));
+ }
+}
+
+internal sealed class RhythmHitView : Control
+{
+ private string _name = "Kick", _caption = "";
+ private double _decaySec = 0.3, _pitchSec, _windowSec = 1, _punch = 0.5, _flash;
+
+ /// <summary>Drag gesture: begin, a change (Δdecay, Δtune in normalized units), end.</summary>
+ public Action? DragBegin, DragEnd;
+ public Action<double, double>? Dragged;
+
+ private Point _last;
+ private bool _dragging;
+
+ public RhythmHitView()
+ {
+ Cursor = new Cursor(StandardCursorType.SizeAll);
+ ClipToBounds = true;
+ }
+
+ public void Set(string name, double decaySec, double pitchSec, double windowSec, double punch, double flash, string caption)
+ {
+ _name = name; _decaySec = decaySec; _pitchSec = pitchSec; _windowSec = Math.Max(0.05, windowSec);
+ _punch = punch; _flash = flash; _caption = caption;
+ InvalidateVisual();
+ }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ _last = e.GetPosition(this); _dragging = true;
+ e.Pointer.Capture(this);
+ DragBegin?.Invoke();
+ e.Handled = true;
+ }
+
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ if (!_dragging) return;
+ var p = e.GetPosition(this);
+ double fine = (e.KeyModifiers & KeyModifiers.Shift) != 0 ? 0.25 : 1.0;
+ double dx = (p.X - _last.X) / Math.Max(40, Bounds.Width) * fine;
+ double dy = -(p.Y - _last.Y) / Math.Max(40, Bounds.Height) * fine;
+ _last = p;
+ Dragged?.Invoke(dx, dy);
+ }
+
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ if (!_dragging) return;
+ _dragging = false;
+ e.Pointer.Capture(null);
+ DragEnd?.Invoke();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w < 20 || h < 20) return;
+ NotaGraph.Window(ctx, new Rect(0, 0, w, h));
+
+ const double x0 = 8, top = 20;
+ double baseY = h - 20, x1 = w - 4;
+ ctx.DrawLine(NotaGraph.GridPen, new Point(1, baseY + 2), new Point(w - 1, baseY + 2));
+ // The trigger.
+ ctx.DrawLine(new Pen(NotaPalette.Wash(NotaPalette.Teal, 0x80), 1), new Point(x0, 1), new Point(x0, h - 1));
+
+ double span = x1 - x0 - 2;
+ double X(double sec) => x0 + 2 + Math.Min(1.0, sec / _windowSec) * span;
+
+ // The pitch drop (Kick / Tom) — or, for the other voices, the attack click by Punch.
+ if (_pitchSec > 0)
+ {
+ var pg = new StreamGeometry();
+ using (var g = pg.Open())
+ {
+ g.BeginFigure(new Point(x0 + 2, top + 6), false);
+ for (double x = x0 + 2; x <= x1; x += 2)
+ {
+ double t = (x - x0 - 2) / span * _windowSec;
+ double e = Math.Exp(-6.9 * t / _pitchSec * 0.5);
+ g.LineTo(new Point(x, baseY - (baseY - top - 6) * (0.18 + 0.82 * e)));
+ }
+ }
+ ctx.DrawGeometry(null, NotaGraph.SecondaryPen(NotaPalette.AccentDim, 1.2), pg);
+ }
+ else if (_punch > 0.02)
+ {
+ double ch = (baseY - top) * (0.25 + 0.6 * _punch);
+ ctx.DrawLine(NotaGraph.SecondaryPen(NotaPalette.AccentDim, 1.2), new Point(x0 + 4, baseY), new Point(x0 + 4, baseY - ch));
+ }
+
+ // The amp contour: a fast rise, then the decay (−20 dB at the Decay time, so the tail reads).
+ var ag = new StreamGeometry();
+ using (var g = ag.Open())
+ {
+ g.BeginFigure(new Point(x0 - 2, h - 4), false);
+ g.LineTo(new Point(x0 + 2, top));
+ double end = X(_decaySec * 2.5);
+ for (double x = x0 + 3; x <= x1; x += 1.5)
+ {
+ double t = (x - x0 - 2) / span * _windowSec;
+ double e = Math.Exp(-2.3 * t / Math.Max(1e-3, _decaySec));
+ g.LineTo(new Point(x, baseY - (baseY - top) * e));
+ if (x > end) { g.LineTo(new Point(x1, baseY)); break; }
+ }
+ }
+ var ampInk = _flash > 0.3 ? NotaPalette.AccentBright : NotaPalette.Accent;
+ ctx.DrawGeometry(null, new Pen(ampInk, NotaGraph.PrimaryWidth, lineCap: PenLineCap.Round, lineJoin: PenLineJoin.Round), ag);
+
+ NotaGraph.Title(ctx, new Rect(0, 0, w, h), "HIT");
+ RhythmInk.TopRight(ctx, w, _name, NotaPalette.AccentBright);
+ RhythmInk.BottomRight(ctx, w, h, _caption);
+ }
+}
+
+internal sealed class RhythmSampleView : Control
+{
+ private float[] _peaks = Array.Empty<float>();
+ private string _name = "", _caption = "";
+ private double _start, _end = 1, _pos = -1;
+ private bool _reverse, _has;
+ private IBrush _hue = NotaPalette.Teal;
+
+ /// <summary>A handle drag: which (0 Start, 1 End), then its new place 0..1 of the file.</summary>
+ public Action<int>? DragBegin, DragEnd;
+ public Action<int, double>? Dragged;
+ /// <summary>Double-click: load a file.</summary>
+ public Action? LoadRequested;
+
+ private int _drag = -1;
+
+ public RhythmSampleView() { ClipToBounds = true; }
+
+ public void SetSamples(float[] interleaved, int channels)
+ {
+ const int cols = 64;
+ var p = new float[cols];
+ channels = Math.Max(1, channels);
+ long frames = interleaved.Length / channels;
+ if (frames > 0)
+ for (int c = 0; c < cols; c++)
+ {
+ long a = frames * c / cols, b = Math.Max(a + 1, frames * (c + 1) / cols);
+ float mx = 0;
+ for (long f = a; f < b && f < frames; f++)
+ for (int ch = 0; ch < channels; ch++) mx = Math.Max(mx, Math.Abs(interleaved[f * channels + ch]));
+ p[c] = Math.Min(1f, mx);
+ }
+ _peaks = p;
+ _has = frames > 0;
+ InvalidateVisual();
+ }
+
+ public void Set(string name, IBrush hue, double start, double end, bool reverse, double pos, string caption)
+ {
+ _name = name; _hue = hue; _start = start; _end = end; _reverse = reverse; _pos = pos; _caption = caption;
+ InvalidateVisual();
+ }
+
+ private const double Pad = 6;
+ private double X(double f) => Pad + Math.Clamp(f, 0, 1) * Math.Max(1, Bounds.Width - 2 * Pad);
+ private double F(double x) => Math.Clamp((x - Pad) / Math.Max(1, Bounds.Width - 2 * Pad), 0, 1);
+
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ var p = e.GetPosition(this);
+ if (_drag >= 0) { Dragged?.Invoke(_drag, F(p.X)); return; }
+ bool near = _has && (Math.Abs(p.X - X(_start)) < 6 || Math.Abs(p.X - X(_end)) < 6);
+ Cursor = near ? new Cursor(StandardCursorType.SizeWestEast) : new Cursor(StandardCursorType.Hand);
+ }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ e.Handled = true;
+ if (e.ClickCount >= 2 || !_has) { LoadRequested?.Invoke(); return; }
+ var p = e.GetPosition(this);
+ _drag = Math.Abs(p.X - X(_start)) <= Math.Abs(p.X - X(_end)) ? 0 : 1;
+ e.Pointer.Capture(this);
+ DragBegin?.Invoke(_drag);
+ Dragged?.Invoke(_drag, F(p.X));
+ }
+
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ if (_drag < 0) return;
+ int d = _drag; _drag = -1;
+ e.Pointer.Capture(null);
+ DragEnd?.Invoke(d);
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w < 20 || h < 20) return;
+ NotaGraph.Window(ctx, new Rect(0, 0, w, h));
+ double mid = (14 + h - 12) / 2, amp = (h - 26) / 2;
+ ctx.DrawLine(NotaGraph.GridPen, new Point(1, mid), new Point(w - 1, mid));
+ NotaGraph.Title(ctx, new Rect(0, 0, w, h), "SAMPLE");
+ if (!_has)
+ {
+ var t = RhythmInk.Mono("double-click or drop a file", NotaPalette.TextTertiary);
+ ctx.DrawText(t, new Point((w - t.Width) / 2, mid - t.Height / 2));
+ return;
+ }
+
+ var inPen = new Pen(_hue, 2.2, lineCap: PenLineCap.Round);
+ var outPen = new Pen(NotaPalette.BorderStrong, 2.2, lineCap: PenLineCap.Round);
+ int n = _peaks.Length, bars = Math.Max(4, (int)((w - 2 * Pad) / 5));
+ for (int i = 0; i < bars; i++)
+ {
+ double f = (i + 0.5) / bars, x = X(f);
+ double a = Math.Max(0.5, _peaks[Math.Min(n - 1, (int)(f * n))] * amp);
+ bool inside = f >= _start && f <= _end;
+ ctx.DrawLine(inside ? inPen : outPen, new Point(x, mid - a), new Point(x, mid + a));
+ }
+
+ var brass = new Pen(NotaPalette.Accent, 1);
+ var dashed = new Pen(NotaPalette.Accent, 1) { DashStyle = new DashStyle(new double[] { 3, 3 }, 0) };
+ double xs = X(_start), xe = X(_end);
+ ctx.DrawLine(_reverse ? dashed : brass, new Point(xs, 1), new Point(xs, h - 1));
+ ctx.DrawLine(_reverse ? brass : dashed, new Point(xe, 1), new Point(xe, h - 1));
+ if (_pos >= 0)
+ {
+ double xp = X(_pos);
+ ctx.DrawLine(new Pen(NotaPalette.TealBright, 1), new Point(xp, 12), new Point(xp, h - 12));
+ }
+
+ RhythmInk.TopRight(ctx, w, _name, NotaPalette.AccentBright);
+ RhythmInk.BottomRight(ctx, w, h, _caption);
+ }
+}
+
+internal sealed class RhythmStepStrip : Control
+{
+ private const int N = RhythmModel.Steps;
+ private const double Gap = 2, LaneH = 4, LaneGap = 3;
+
+ public readonly bool[] On = new bool[N], Acc = new bool[N];
+ public readonly float[] Vel = new float[N];
+ private int _head = -1;
+
+ /// <summary>A step changed (its on / velocity / accent now in the arrays).</summary>
+ public Action<int>? Commit;
+ /// <summary>Right-click on a step: the card shows its menu.</summary>
+ public Action<int>? StepMenu;
+
+ private int _pressStep = -1, _lastPaint = -1;
+ private bool _paintOn, _velMode;
+ private Point _pressAt;
+ private float _pressVel;
+
+ public RhythmStepStrip()
+ {
+ Cursor = new Cursor(StandardCursorType.Hand);
+ ToolTip.SetTip(this, "Click: step on / off · Shift-click: accent · Alt-click: quiet step\nDrag across to paint · drag up / down or scroll to set the velocity · right-click for more");
+ }
+
+ public void SetHead(int head) { if (head != _head) { _head = head; InvalidateVisual(); } }
+ public void Changed() => InvalidateVisual();
+
+ private double CellW => (Bounds.Width - Gap * (N - 1)) / N;
+ private int StepAt(double x) => Math.Clamp((int)Math.Floor(x / (CellW + Gap)), 0, N - 1);
+
+ private void Put(int s, bool on, float vel, bool acc)
+ {
+ if (On[s] == on && Math.Abs(Vel[s] - vel) < 1e-4f && Acc[s] == acc) return;
+ On[s] = on; Vel[s] = vel; Acc[s] = acc && on;
+ Commit?.Invoke(s);
+ InvalidateVisual();
+ }
+
+ private float OnVel(int s) => Vel[s] > 0.01f ? Vel[s] : RhythmModel.NormalVel;
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ var pt = e.GetCurrentPoint(this);
+ int s = StepAt(pt.Position.X);
+ e.Handled = true;
+ if (pt.Properties.IsRightButtonPressed) { StepMenu?.Invoke(s); return; }
+ if (!pt.Properties.IsLeftButtonPressed) return;
+ var mods = e.KeyModifiers;
+ if ((mods & KeyModifiers.Shift) != 0)
+ {
+ bool acc = !(On[s] && Acc[s]);
+ Put(s, true, acc ? Math.Max(OnVel(s), RhythmModel.NormalVel) : OnVel(s), acc);
+ return;
+ }
+ if ((mods & KeyModifiers.Alt) != 0)
+ {
+ bool quiet = On[s] && !Acc[s] && Vel[s] < RhythmModel.QuietBelow;
+ Put(s, true, quiet ? RhythmModel.NormalVel : RhythmModel.QuietVel, false);
+ return;
+ }
+ _paintOn = !On[s];
+ Put(s, _paintOn, OnVel(s), Acc[s]);
+ _pressStep = s; _lastPaint = s; _velMode = false;
+ _pressAt = pt.Position; _pressVel = Vel[s];
+ e.Pointer.Capture(this);
+ }
+
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ if (_pressStep < 0) return;
+ var p = e.GetPosition(this);
+ double dx = p.X - _pressAt.X, dy = p.Y - _pressAt.Y;
+ if (!_velMode && _lastPaint == _pressStep && Math.Abs(dy) > 4 && Math.Abs(dy) > Math.Abs(dx) && On[_pressStep])
+ _velMode = true;
+ if (_velMode)
+ {
+ float v = (float)Math.Clamp(_pressVel - dy / 60.0, 0.05, 1.0);
+ Put(_pressStep, true, v, Acc[_pressStep]);
+ return;
+ }
+ int s = StepAt(p.X);
+ if (s == _lastPaint) return;
+ int dir = s > _lastPaint ? 1 : -1;
+ for (int k = _lastPaint + dir; k != s + dir; k += dir) Put(k, _paintOn, OnVel(k), Acc[k]);
+ _lastPaint = s;
+ }
+
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ if (_pressStep < 0) return;
+ _pressStep = -1;
+ e.Pointer.Capture(null);
+ }
+
+ protected override void OnPointerWheelChanged(PointerWheelEventArgs e)
+ {
+ int s = StepAt(e.GetPosition(this).X);
+ if (!On[s]) return;
+ Put(s, true, (float)Math.Clamp(Vel[s] + (e.Delta.Y > 0 ? 0.05 : -0.05), 0.05, 1.0), Acc[s]);
+ e.Handled = true;
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w < N * 4 || h < 12) return;
+ double cw = CellW, cellH = h - LaneH - LaneGap;
+ var offPen = new Pen(NotaPalette.GraphBorder, 1);
+ var beatPen = new Pen(NotaPalette.BorderDefault, 1);
+ var quietPen = new Pen(NotaPalette.BorderBrass, 1);
+ var headPen = new Pen(NotaPalette.TealBright, 1);
+ for (int s = 0; s < N; s++)
+ {
+ double x = s * (cw + Gap);
+ var r = new Rect(x + 0.5, 0.5, cw - 1, cellH - 1);
+ bool on = On[s], acc = on && Acc[s], quiet = on && !acc && Vel[s] < RhythmModel.QuietBelow;
+ if (!on) ctx.DrawRectangle(NotaPalette.BgSunken, s % 4 == 0 ? beatPen : offPen, r, 2, 2);
+ else if (quiet) ctx.DrawRectangle(NotaPalette.AccentSubtle, quietPen, r, 2, 2);
+ else ctx.DrawRectangle(acc ? NotaPalette.AccentBright : NotaPalette.Accent, null, r, 2, 2);
+ if (on && !quiet)
+ {
+ var ft = RhythmInk.Mono((s + 1).ToString(NotaNum.Culture), NotaPalette.TextOnAccent);
+ ctx.DrawText(ft, new Point(x + (cw - ft.Width) / 2, 1));
+ }
+ if (s == _head) ctx.DrawRectangle(null, headPen, r, 2, 2);
+
+ // The velocity lane: teal by strength — accent light, normal teal, quiet deep.
+ var lane = new Rect(x, h - LaneH, cw, LaneH);
+ IBrush li = !on ? NotaPalette.SurfaceRaised
+ : acc ? NotaPalette.TealBright
+ : NotaPalette.Wash(NotaPalette.Teal, (byte)Math.Clamp(70 + Vel[s] * 185, 70, 255));
+ ctx.DrawRectangle(li, null, lane, 1, 1);
+ }
+ }
+}
diff --git a/src/managed/Nota.App/Controls/RhythmWaveViz.cs b/src/managed/Nota.App/Controls/RhythmWaveViz.cs
deleted file mode 100644
index c1f81715..00000000
--- a/src/managed/Nota.App/Controls/RhythmWaveViz.cs
+++ /dev/null
@@ -1,56 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
-//
-// Nota Rhythm — the sample-mode waveform preview shown in the voice panel when a voice loads
-// a one-shot. A simple filled peak envelope computed from the decoded sample (interleaved).
-
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Media;
-
-namespace Nota.App;
-
-internal sealed class RhythmWaveViz : Control
-{
- private float[] _peaks = System.Array.Empty<float>(); // per-column max |amp|, 0..1
- private static readonly IBrush Fill = NotaPalette.Wash(NotaPalette.Teal, 0xD9);
- private static readonly IPen Mid = new Pen(NotaPalette.BorderDefault, 1);
-
- public void SetSamples(float[] interleaved, int channels)
- {
- int cols = 140;
- var p = new float[cols];
- if (interleaved.Length > 0 && channels > 0)
- {
- long frames = interleaved.Length / channels;
- for (int c = 0; c < cols; c++)
- {
- long a = frames * c / cols, b = System.Math.Max(a + 1, frames * (c + 1) / cols);
- float mx = 0;
- for (long f = a; f < b; f++)
- for (int ch = 0; ch < channels; ch++)
- { float v = System.Math.Abs(interleaved[f * channels + ch]); if (v > mx) mx = v; }
- p[c] = System.Math.Min(1f, mx);
- }
- }
- _peaks = p;
- InvalidateVisual();
- }
-
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height, mid = h * 0.5;
- if (w < 4 || h < 4) return;
- ctx.DrawLine(Mid, new Point(0, mid), new Point(w, mid));
- if (_peaks.Length == 0) return;
- var geo = new StreamGeometry();
- using (var g = geo.Open())
- {
- g.BeginFigure(new Point(0, mid), true);
- for (int i = 0; i < _peaks.Length; i++) { double x = w * i / (_peaks.Length - 1); g.LineTo(new Point(x, mid - _peaks[i] * (mid - 1))); }
- for (int i = _peaks.Length - 1; i >= 0; i--) { double x = w * i / (_peaks.Length - 1); g.LineTo(new Point(x, mid + _peaks[i] * (mid - 1))); }
- g.EndFigure(true);
- }
- ctx.DrawGeometry(Fill, null, geo);
- }
-}
diff --git a/src/managed/Nota.App/DeviceCards/Instruments/RhythmInstrumentCard.cs b/src/managed/Nota.App/DeviceCards/Instruments/RhythmInstrumentCard.cs
index 96354ace..16bfca67 100644
--- a/src/managed/Nota.App/DeviceCards/Instruments/RhythmInstrumentCard.cs
+++ b/src/managed/Nota.App/DeviceCards/Instruments/RhythmInstrumentCard.cs
@@ -1,23 +1,30 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Detail · Devices — built-in Nota Rhythm editor (instrument kind 12), built to the
-// shared 900×260 card shell. Layout:
-// KIT (left) — eight selectable drum voices (SYN tag); the selection drives the rest.
-// VOICE (center) — Synth/Sample source (Sample disabled in Phase 1), engine label, the HIT
-// preview, and the six engine knobs of the selected voice.
-// PERFORM (right)— Swing / Humanize / Accent.
-// STEP (bottom) — the 16 step buttons for the selected voice + bank (click toggles,
-// shift-click accents), a per-step velocity row, and a teal playhead.
-// The 7 per-voice knobs + 4 globals are plugin-params → automation / persist / clone. The
-// step patterns are structural state, edited via engine.InstrumentAction and read from the
-// instrument state blob.
+// Detail · Devices — the Nota Rhythm editor (instrument kind 12): an eight-voice drum
+// machine in the 700 × 260 card the almanac draws for it. Reading order, left to right:
+//
+// KIT 104 the voices — a hue dot, the name, SYN / SMP. Click selects and plays the
+// voice; drop a file on one to load it as a sample; right-click for more.
+// VOICE the selected voice's editor. Synth: the HIT contour (drag it — across is
+// Decay, up / down Tune) and Tune · Decay · Punch · Tone · Drive · Level.
+// Sample: the file with its Start / End region (drag the lines), Reverse,
+// and Start · Length · Tune (st) · Decay · Drive · Level.
+// PERFORM 186 Swing · Human · Accent (teal — they shape the playing, not the sound),
+// Master and Glue (the bus compressor), the output meter.
+// STEP a full-width strip: the selected voice's sixteen steps in bank A–D, a
+// velocity lane under them. Brass is the step, bright brass the accent, a
+// brass outline a quiet step; teal is the playhead and the velocity.
+// status what the voice is and where its steps are · voices · rate · tempo · CPU.
+//
+// Every knob is a plugin param → automation / persist / clone, followed live. The steps are
+// structural state, edited via engine.InstrumentAction and read from the state blob; the
+// engine bumps an edit revision in its scope, so an edit made elsewhere (MCP) shows up here.
using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
-using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Layout;
@@ -25,6 +32,7 @@ using Avalonia.Media;
using Avalonia.Platform.Storage;
using Nota.Application;
using static Nota.App.DeviceCardKit;
+using RM = Nota.Application.RhythmModel;
namespace Nota.App;
@@ -32,29 +40,14 @@ internal sealed class RhythmInstrumentCard : IInstrumentCard
{
public bool BodyOnly => true;
public string Subtitle => "DRUM MACHINE";
- public double CardWidth => 900;
-
- // action ids — must match RhythmMachine::Act.
- private const int A_ToggleStep = 0, A_SetVel = 1, A_ToggleAccent = 2, A_SelectBank = 3, A_ClearBank = 4, A_SelectVoice = 5, A_SetSource = 6;
- private const int Voices = 8, Steps = 16;
-
- private static readonly string[] Names = { "Kick", "Snare", "Clap", "Rim", "Closed Hat", "Open Hat", "Tom", "Perc" };
- private static readonly string[] Engines = { "Analog", "Noise", "Clap", "Rim", "Metal", "Metal", "Analog", "Ring" };
- // Kit-voice identity hues — one dot per voice, themed through NotaPalette.Ink.
- private static readonly string[] Dots = { "#C4756A", "#D8A03D", "#7FC9C6", "#B58AC4", "#7E8A6A", "#8FB56A", "#6D8FB5", "#5B9E9C" };
-
- private static readonly IBrush Ink = NotaPalette.TextOnAccent;
- private static readonly IBrush Panel = NotaPalette.SurfaceInset;
- private static readonly IBrush Inset = NotaPalette.BgSunken;
- private static readonly IBrush SeqBg = NotaPalette.SurfaceDeep;
- private static readonly IBrush Border2 = NotaPalette.BorderDefault;
- private static readonly IBrush StepOff = NotaPalette.BgSunken;
- private static readonly IBrush StepOn = NotaPalette.Accent;
- private static readonly IBrush StepAcc = NotaPalette.AccentBright; // accented step: the hotter brass, still flat
- private static readonly IBrush TealB = NotaPalette.Teal;
- private static readonly IBrush TealBright = NotaPalette.TealBright;
- private static readonly IBrush Muted = NotaPalette.TextTertiary;
- private static readonly IBrush VelFill = NotaPalette.Ink("#A7B58A");
+ public double CardWidth => 700;
+
+ public string? VoiceLabel(IAudioEngine engine, int trackId, int active) => $"{Math.Max(0, active)}/{RM.Voices}";
+
+ private const double KitW = 104, RailW = 186, StepH = 46, HeadH = 18, StatusH = 18, GraphW = 112;
+
+ // Kit-voice identity hues — one per voice, painted only through NotaPalette.Ink.
+ private static readonly string[] Dots = { "#C77F55", "#D8A03D", "#3E8E8E", "#7A6FB0", "#9AA64A", "#58B368", "#5AA0B8", "#B57286" };
public Control Build(DeviceCardContext ctx)
{
@@ -63,268 +56,608 @@ internal sealed class RhythmInstrumentCard : IInstrumentCard
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;
+ float G(string id) => I(id) is var i and >= 0 ? engine.PluginParamGet(track, -1, i) : 0f;
+ void SetP(string id, float v) { if (I(id) is var i and >= 0) engine.PluginParamSet(track, -1, i, Math.Clamp(v, 0f, 1f)); }
+ void Begin(string id) { if (I(id) >= 0) engine.BeginAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id); }
+ void End(string id) { if (I(id) >= 0) engine.EndAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id); }
+ void Write(string id, float v) { Begin(id); SetP(id, v); End(id); }
void Act(int id, int iarg, float farg = 0f) => engine.InstrumentAction(track, id, iarg, farg);
- // ---- read pattern + selection from the instrument state blob ----
- byte[] st = engine.GetPluginState(track, -1);
- int bankByte = 4 + pc * 4, patBase = bankByte + 4;
- int sel = st.Length > bankByte + 1 ? Math.Clamp(st[bankByte + 1], (byte)0, (byte)(Voices - 1)) : 0;
- int bank = st.Length > bankByte ? Math.Clamp(st[bankByte], (byte)0, (byte)3) : 0;
- int Ix(int v, int s) => patBase + ((bank * Voices + v) * Steps + s) * 3;
- bool On(int v, int s) { int i = Ix(v, s); return i + 0 < st.Length && st[i] != 0; }
- float Vel(int v, int s) { int i = Ix(v, s) + 1; return i < st.Length ? st[i] / 255f : 0.7f; }
- bool Acc(int v, int s) { int i = Ix(v, s) + 2; return i < st.Length && st[i] != 0; }
+ // ---- state ----------------------------------------------------------------------
+ var pat = RM.Parse(engine.GetPluginState(track, -1), pc);
+ int sel = pat.SelectedVoice;
+ int bank = pat.CurrentBank;
+ var isSample = new bool[RM.Voices];
+ for (int v = 0; v < RM.Voices; v++) isSample[v] = engine.RhythmVoiceSource(track, v) == 1;
+ long sid = engine.TryGetRhythmVoiceInfo(track, sel, out var vinfo) ? vinfo.SampleId : 0;
+ bool sampleMode = isSample[sel] && sid != 0;
+ string sampleName = sid != 0 ? engine.SampleName(sid) : "";
+ if (sampleName.Length == 0 && sid != 0) sampleName = "sample";
+ double sampleSecs = sid != 0 && engine.TryGetSampleInfo(sid, out var sinfo) && sinfo.SampleRate > 0 ? sinfo.Frames / sinfo.SampleRate : 0;
+ string P(string p) => RM.Id(sel, p);
+ IBrush Hue(int v) => NotaPalette.Ink(Dots[v]);
var readouts = new List<Action>();
- TextBlock Mono(string t, IBrush c, double fs = 9) { var tb = new TextBlock { Text = t, FontSize = fs, Foreground = c, VerticalAlignment = VerticalAlignment.Center }; tb.BindResource(TextBlock.FontFamilyProperty, "Font.Mono"); return tb; }
- TextBlock Sec(string t, IBrush? c = null) => new() { Text = t, FontSize = 8, FontWeight = FontWeight.Bold, Foreground = c ?? Muted, VerticalAlignment = VerticalAlignment.Center };
+ var scope = new float[RM.ScopeLength];
+ int lastRev = -1;
+ float flashSel = 0, posSel = -1;
+ var strip = new RhythmStepStrip();
+ var bankCells = new Border[RM.Banks];
+ var bankTexts = new TextBlock[RM.Banks];
- // ---- KIT column -----------------------------------------------------
- var kitList = new StackPanel { Spacing = 1 };
- var kitDots = new Ellipse[Voices];
- for (int v = 0; v < Voices; v++)
+ static TextBlock Cap(string t, IBrush? c = null) => new()
{
- int vv = v; bool selRow = v == sel;
- bool isSmp = engine.RhythmVoiceSource(track, v) == 1;
- var dot = new Ellipse { Width = 7, Height = 7, Fill = NotaPalette.Ink(Dots[v]), VerticalAlignment = VerticalAlignment.Center };
- kitDots[v] = dot;
- var nm = new TextBlock { Text = Names[v], FontSize = 9, Foreground = selRow ? NotaPalette.AccentBright : NotaPalette.TextStrong, VerticalAlignment = VerticalAlignment.Center };
- var tag = new TextBlock { Text = isSmp ? "SMP" : "SYN", FontSize = 7, FontWeight = FontWeight.Bold, Foreground = isSmp ? TealB : selRow ? Brass : Muted, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Right };
- var row = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), Height = 15, Margin = new Thickness(6, 0) };
- Grid.SetColumn(dot, 0); Grid.SetColumn(nm, 1); Grid.SetColumn(tag, 2);
- nm.Margin = new Thickness(6, 0, 0, 0);
- var rowBox = new Border { CornerRadius = NotaRadius.Control, Cursor = new Cursor(StandardCursorType.Hand), Child = row, Background = selRow ? NotaPalette.Wash(NotaPalette.Accent, 0x24) : Brushes.Transparent, BorderBrush = selRow ? NotaPalette.BorderBrass : Brushes.Transparent, BorderThickness = new Thickness(1) };
- row.Children.Add(dot); row.Children.Add(nm); row.Children.Add(tag);
- rowBox.PointerPressed += (_, _) => { Act(A_SelectVoice, vv); ctx.RequestRebuild(); };
- // Drop an audio file (browser or Finder) onto a voice → load it as that voice's sample.
- ToolTip.SetTip(rowBox, "Drop a sample to load it into this voice");
- DragDrop.SetAllowDrop(rowBox, true);
- DragDrop.AddDragOverHandler(rowBox, (_, e) => { if (BrowserView.IsAcceptableDrag(e)) { e.DragEffects = DragDropEffects.Copy; rowBox.BorderBrush = TealB; ctx.HideDropGlow(); } });
- DragDrop.AddDragLeaveHandler(rowBox, (_, _) => rowBox.BorderBrush = selRow ? NotaPalette.BorderBrass : Brushes.Transparent);
- DragDrop.AddDropHandler(rowBox, (_, e) =>
+ Text = t, FontSize = NotaType.KnobLabel, FontWeight = FontWeight.Bold,
+ LetterSpacing = NotaType.SectionLabelTracking, Foreground = c ?? TextTertiary,
+ VerticalAlignment = VerticalAlignment.Center,
+ };
+ static TextBlock Mono(string t, IBrush? c = null, double fs = 7) => new()
+ {
+ Text = t, FontSize = fs, Foreground = c ?? TextSecondary,
+ VerticalAlignment = VerticalAlignment.Center, FontFamily = NotaFonts.MonoFamily,
+ };
+
+ var status = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var meta = Mono("", TextSecondary, 8);
+
+ void Refresh() { foreach (var r in readouts) r(); }
+
+ // ---- shared builders ---------------------------------------------------------------
+ Control PKnob(string id, string label, Func<float, string> fmt, double size = 30, double cellW = 42, string? tip = null)
+ {
+ if (!idx.TryGetValue(id, out var pi)) return new Panel();
+ var value = new TextBlock { Text = fmt(G(id)), Foreground = TextPrimary };
+ var knob = new Knob(G(id), 1.0)
{
+ Accent = true, Default = engine.InstrumentParamDefault(track, pi), Width = size, Height = size,
+ };
+ knob.ValueChanged += v => { engine.PluginParamSet(track, -1, pi, (float)v); value.Text = fmt((float)v); Refresh(); };
+ knob.GestureBegin += () => Begin(id);
+ knob.GestureEnd += () => End(id);
+ ctx.AddInstFader(pi, knob, value, fmt);
+ MidiLearn.Bind(knob, MidiTarget.PluginParam(track, -1, pi), engine.PluginParamName(track, -1, pi));
+ var cell = KnobCell(label, knob, value, cellW);
+ cell.VerticalAlignment = VerticalAlignment.Center;
+ if (tip is not null) ToolTip.SetTip(cell, tip);
+ return cell;
+ }
+
+ Grid Slider(string label, string id, string tip)
+ {
+ int pi = I(id);
+ var row = SliderRow(label, () => G(id), v => { SetP(id, (float)v); Refresh(); }, () => RM.Pct(G(id)), out var sync,
+ begin: pi >= 0 ? () => Begin(id) : null,
+ end: pi >= 0 ? () => End(id) : null,
+ reset: pi >= 0 ? () => { Write(id, engine.InstrumentParamDefault(track, pi)); Refresh(); } : null,
+ labelWidth: 38, valueWidth: 28, modulation: true);
+ row.ColumnSpacing = 6;
+ readouts.Add(sync);
+ ToolTip.SetTip(row, tip);
+ if (pi >= 0) MidiLearn.Bind(row, MidiTarget.PluginParam(track, -1, pi), engine.PluginParamName(track, -1, pi));
+ return row;
+ }
+
+ // A small raised button; a latching one turns brass-washed while on.
+ Border SmallButton(Control content, TextBlock label, Action click, Func<bool>? on = null)
+ {
+ var b = new Border
+ {
+ Height = 14, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Padding = new Thickness(6, 0),
+ Cursor = new Cursor(StandardCursorType.Hand), Child = content, VerticalAlignment = VerticalAlignment.Center,
+ };
+ void Paint()
+ {
+ bool lit = on?.Invoke() ?? false;
+ b.Background = lit ? NotaPalette.AccentSubtle : NotaPalette.SurfaceRaised;
+ b.BorderBrush = lit ? NotaPalette.BorderBrass : BorderDef;
+ label.Foreground = lit ? AccentBright : NotaPalette.TextStrong;
+ }
+ b.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return;
+ click(); Paint(); e.Handled = true;
+ };
+ readouts.Add(Paint);
+ Paint();
+ return b;
+ }
+
+ // A freshly loaded one-shot plays at its own pitch and in full (the synth's tune
+ // default would transpose it); select its voice so the card shows it.
+ void Loaded(int voice)
+ {
+ Write(RM.Id(voice, "tune"), 0.5f);
+ Write(RM.Id(voice, "start"), 0f);
+ Write(RM.Id(voice, "length"), 1f);
+ Act(RM.A_SelectVoice, voice);
+ }
+
+ async void LoadSample(Control anchor, int voice)
+ {
+ var topLevel = TopLevel.GetTopLevel(anchor);
+ if (topLevel is null) return;
+ var files = await topLevel.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
+ {
+ Title = $"Load a sample into {RM.VoiceNames[voice]}", AllowMultiple = false,
+ FileTypeFilter = new[] { new FilePickerFileType("Audio") { Patterns = new[] { "*.wav", "*.flac", "*.mp3", "*.aif", "*.aiff", "*.ogg" } } },
+ });
+ if (files.Count > 0 && files[0].TryGetLocalPath() is { } p && engine.SetRhythmVoiceSample(track, voice, p))
+ {
+ Loaded(voice);
+ ctx.NotifyChanged(); ctx.RequestRebuild();
+ }
+ }
+
+ void AcceptDrops(Control target, int voice, Action<bool> hover)
+ {
+ DragDrop.SetAllowDrop(target, true);
+ DragDrop.AddDragOverHandler(target, (_, e) => { if (BrowserView.IsAcceptableDrag(e)) { e.DragEffects = DragDropEffects.Copy; hover(true); ctx.HideDropGlow(); e.Handled = true; } });
+ DragDrop.AddDragLeaveHandler(target, (_, _) => hover(false));
+ DragDrop.AddDropHandler(target, (_, e) =>
+ {
+ hover(false);
foreach (var it in BrowserView.DroppedItems(e))
- if (it.Path is { Length: > 0 } p) { engine.SetRhythmVoiceSample(track, vv, p); break; }
- ctx.RequestRebuild(); e.Handled = true;
+ if (it.Path is { Length: > 0 } p && engine.SetRhythmVoiceSample(track, voice, p))
+ {
+ Loaded(voice);
+ ctx.NotifyChanged(); ctx.RequestRebuild();
+ break;
+ }
+ e.Handled = true;
});
- kitList.Children.Add(rowBox);
}
- var kitHead = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*") };
- kitHead.Children.Add(Sec("KIT"));
- var kh = Sec("synth or sample"); kh.HorizontalAlignment = HorizontalAlignment.Right; Grid.SetColumn(kh, 1); kitHead.Children.Add(kh);
- var kitScroll = new ScrollViewer
+
+ // ---- KIT ------------------------------------------------------------------------------
+ var kitRows = new Grid { Margin = new Thickness(2) };
+ var kitDots = new Ellipse[RM.Voices];
+ for (int v = 0; v < RM.Voices; v++)
+ {
+ kitRows.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
+ int vv = v; bool on = v == sel;
+ var dot = new Ellipse { Width = 5, Height = 5, Fill = Hue(v), VerticalAlignment = VerticalAlignment.Center };
+ kitDots[v] = dot;
+ var nm = new TextBlock
+ {
+ Text = RM.VoiceNames[v], FontSize = 8, FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal,
+ Foreground = on ? AccentBright : TextPrimary, VerticalAlignment = VerticalAlignment.Center,
+ TextTrimming = TextTrimming.CharacterEllipsis, Margin = new Thickness(5, 0, 4, 0),
+ };
+ var tag = Mono(isSample[v] ? "SMP" : "SYN", on ? AccentBright : TextTertiary);
+ var row = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), Margin = new Thickness(5, 0) };
+ row.Children.Add(dot);
+ Grid.SetColumn(nm, 1); row.Children.Add(nm);
+ Grid.SetColumn(tag, 2); row.Children.Add(tag);
+ IBrush restBorder = on ? NotaPalette.BorderBrass : Brushes.Transparent;
+ var box = new Border
+ {
+ CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand),
+ Background = on ? NotaPalette.AccentSubtle : Brushes.Transparent, BorderBrush = restBorder, Child = row,
+ };
+ ToolTip.SetTip(box, $"{RM.VoiceNames[v]} · MIDI {DeviceCardKit.NoteName(RM.MidiNotes[v])}\nClick: select and play · drop a file to load it · right-click for more");
+ box.PointerPressed += (_, e) =>
+ {
+ var pt = e.GetCurrentPoint(box);
+ e.Handled = true;
+ if (pt.Properties.IsRightButtonPressed) { KitMenu(vv, box); return; }
+ if (!pt.Properties.IsLeftButtonPressed) return;
+ Act(RM.A_Audition, vv, 0.8f);
+ if (vv != sel) { Act(RM.A_SelectVoice, vv); ctx.RequestRebuild(); }
+ };
+ AcceptDrops(box, vv, h => box.BorderBrush = h ? Teal : restBorder);
+ Grid.SetRow(box, v); kitRows.Children.Add(box);
+ }
+ void KitMenu(int v, Control anchor)
+ {
+ var fly = new MenuFlyout();
+ var load = new MenuItem { Header = "Load sample…" };
+ load.Click += (_, _) => LoadSample(anchor, v);
+ fly.Items.Add(load);
+ bool has = engine.TryGetRhythmVoiceInfo(track, v, out var vi) && vi.SampleId != 0;
+ var src = new MenuItem { Header = isSample[v] ? "Play the synth engine" : "Play the loaded sample", IsEnabled = isSample[v] || has };
+ src.Click += (_, _) => { Act(RM.A_SetSource, v, isSample[v] ? 0f : 1f); ctx.NotifyChanged(); ctx.RequestRebuild(); };
+ fly.Items.Add(src);
+ fly.Items.Add(new Separator());
+ var clear = new MenuItem { Header = $"Clear its steps in bank {RM.BankNames[bank]}" };
+ clear.Click += (_, _) => { Act(RM.A_ClearVoice, v); ctx.NotifyChanged(); ReloadPattern(); };
+ fly.Items.Add(clear);
+ fly.ShowAt(anchor);
+ }
+ var kitHead = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), Margin = new Thickness(7, 0) };
+ kitHead.Children.Add(Cap("KIT"));
+ var kitSub = Mono("syn/smp", NotaPalette.TextDisabled); kitSub.HorizontalAlignment = HorizontalAlignment.Right;
+ Grid.SetColumn(kitSub, 1); kitHead.Children.Add(kitSub);
+ var kit = Section(kitHead, kitRows);
+ kit.Width = KitW;
+
+ // ---- VOICE ----------------------------------------------------------------------------
+ var srcSeg = Segments(new[] { "Synth", "Sample" }, () => sampleMode ? 1 : 0, i =>
+ {
+ if (i == 1)
+ {
+ if (sid != 0) { Act(RM.A_SetSource, sel, 1f); ctx.NotifyChanged(); ctx.RequestRebuild(); }
+ else LoadSample(kit, sel);
+ }
+ else if (sampleMode) { Act(RM.A_SetSource, sel, 0f); ctx.NotifyChanged(); ctx.RequestRebuild(); }
+ }, out _, padX: 6, fontSize: 7);
+ ToolTip.SetTip(srcSeg, "Synth: the voice's own engine · Sample: a loaded one-shot (loads one if the voice has none)");
+
+ var folder = new Avalonia.Controls.Shapes.Path
{
- Content = kitList, Margin = new Thickness(0, 5, 0, 0),
- HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,
- VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
+ Data = Geometry.Parse("M1 3.5 L4.5 3.5 L5.6 2 L11 2 L11 10 L1 10 Z"), Stroke = NotaPalette.TextStrong, StrokeThickness = 1.2,
+ Width = 7, Height = 7, Stretch = Stretch.Uniform, VerticalAlignment = VerticalAlignment.Center,
};
- var kitDock = new DockPanel { LastChildFill = true };
- DockPanel.SetDock(kitHead, Dock.Top); kitDock.Children.Add(kitHead);
- kitDock.Children.Add(kitScroll);
- var kitCol = new Border { Width = 188, BorderBrush = Border2, BorderThickness = new Thickness(0, 0, 1, 0), Padding = new Thickness(8, 7), Child = kitDock };
-
- // ---- VOICE column ---------------------------------------------------
- var voiceHead = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 };
- voiceHead.Children.Add(new TextBlock { Text = "VOICE — ", FontSize = 8, FontWeight = FontWeight.Bold, Foreground = Muted, VerticalAlignment = VerticalAlignment.Center });
- voiceHead.Children.Add(new TextBlock { Text = Names[sel], FontSize = 9, FontWeight = FontWeight.Bold, Foreground = TextPrimary, VerticalAlignment = VerticalAlignment.Center });
- // Synth | Sample source toggle (Phase 2 — Sample loads a one-shot via the Sampler).
- int voiceSrc = engine.RhythmVoiceSource(track, sel);
- long voiceSid = engine.TryGetRhythmVoiceInfo(track, sel, out var vinfo) ? vinfo.SampleId : 0;
- bool sampleMode = voiceSrc == 1 && voiceSid != 0;
- var srcSeg = new Border { Background = Inset, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, Padding = new Thickness(1), HorizontalAlignment = HorizontalAlignment.Right };
- Border SrcChip(string text, bool on, IBrush onBg)
- => new() { Background = on ? onBg : Brushes.Transparent, CornerRadius = NotaRadius.Control, Padding = new Thickness(9, 2), Cursor = new Cursor(StandardCursorType.Hand),
- Child = new TextBlock { Text = text, FontSize = 9, FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal, Foreground = on ? NotaPalette.TextOnAccent : Muted } };
- var synthChip = SrcChip("Synth", !sampleMode, Brass);
- var sampleChip = SrcChip("Sample", sampleMode, TealB);
- synthChip.PointerPressed += (_, _) => { Act(A_SetSource, sel, 0f); ctx.RequestRebuild(); };
- async void LoadSampleDialog(Control anchor)
+ var fileText = new TextBlock
{
- var top = TopLevel.GetTopLevel(anchor);
- if (top is null) return;
- var files = await top.StorageProvider.OpenFilePickerAsync(new Avalonia.Platform.Storage.FilePickerOpenOptions
+ Text = sampleMode ? sampleName : "Load file…", FontSize = 7, FontWeight = FontWeight.SemiBold, MaxWidth = 90,
+ TextTrimming = TextTrimming.CharacterEllipsis, VerticalAlignment = VerticalAlignment.Center,
+ };
+ if (sampleMode) fileText.FontFamily = NotaFonts.MonoFamily;
+ var fileBtn = SmallButton(new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Children = { folder, fileText } }, fileText,
+ () => LoadSample(kit, sel), () => sampleMode);
+ readouts.Add(() => folder.Stroke = sampleMode ? AccentBright : NotaPalette.TextStrong);
+ ToolTip.SetTip(fileBtn, sampleMode ? $"{sampleName} — click to load another file" : "Load a one-shot into this voice (or drop a file on the voice)");
+
+ var voiceHead = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Margin = new Thickness(7, 0), VerticalAlignment = VerticalAlignment.Center };
+ voiceHead.Children.Add(Cap("VOICE"));
+ voiceHead.Children.Add(new TextBlock { Text = RM.VoiceNames[sel], FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = TextPrimary, VerticalAlignment = VerticalAlignment.Center });
+ var voiceTools = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, Margin = new Thickness(0, 0, 6, 0), VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Right };
+ voiceTools.Children.Add(srcSeg);
+ voiceTools.Children.Add(fileBtn);
+ if (sampleMode)
+ {
+ var revText = new TextBlock { Text = "Reverse", FontSize = 7, FontWeight = FontWeight.SemiBold, VerticalAlignment = VerticalAlignment.Center };
+ var rev = SmallButton(revText, revText,
+ () => { Write(P("reverse"), G(P("reverse")) >= 0.5f ? 0f : 1f); Refresh(); }, () => G(P("reverse")) >= 0.5f);
+ ToolTip.SetTip(rev, "Play the region back to front");
+ if (I(P("reverse")) is var ri and >= 0) MidiLearn.Bind(rev, MidiTarget.PluginParam(track, -1, ri), engine.PluginParamName(track, -1, ri));
+ voiceTools.Children.Add(rev);
+ }
+ var voiceHeadRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*") };
+ voiceHeadRow.Children.Add(voiceHead);
+ Grid.SetColumn(voiceTools, 1); voiceHeadRow.Children.Add(voiceTools);
+
+ Control graph;
+ if (sampleMode)
+ {
+ var sv = new RhythmSampleView { Width = GraphW };
+ if (engine.TryGetSampleInfo(sid, out var si)) sv.SetSamples(engine.ReadSample(sid), si.Channels);
+ sv.LoadRequested = () => LoadSample(sv, sel);
+ sv.DragBegin = _ => { Begin(P("start")); Begin(P("length")); };
+ sv.DragEnd = _ => { End(P("start")); End(P("length")); };
+ sv.Dragged = (which, f) =>
+ {
+ float st = G(P("start")), en = (float)RM.RegionEnd(st, G(P("length")));
+ if (which == 0) { float ns = (float)Math.Clamp(f, 0, en - 0.01); SetP(P("start"), ns); SetP(P("length"), en - ns); }
+ else SetP(P("length"), (float)Math.Clamp(f - st, 0.01, 1.0));
+ Refresh();
+ };
+ readouts.Add(() =>
{
- Title = "Load drum sample", AllowMultiple = false,
- FileTypeFilter = new[] { new Avalonia.Platform.Storage.FilePickerFileType("Audio") { Patterns = new[] { "*.wav", "*.flac", "*.mp3", "*.aif", "*.aiff", "*.ogg" } } },
+ float st = G(P("start")), en = (float)RM.RegionEnd(st, G(P("length")));
+ string secs = sampleSecs > 0 ? " · " + NotaNum.Unit((en - st) * sampleSecs, "0.00", "s") : "";
+ sv.Set(sampleName, Hue(sel), st, en, G(P("reverse")) >= 0.5f, posSel, $"{RM.Pct(st)} → {RM.Pct(en)}{secs}");
});
- if (files.Count > 0 && files[0].TryGetLocalPath() is { } p) { engine.SetRhythmVoiceSample(track, sel, p); ctx.RequestRebuild(); }
+ ToolTip.SetTip(sv, "Drag the brass lines to set Start and End · double-click to load another file");
+ AcceptDrops(sv, sel, _ => { });
+ graph = sv;
}
- sampleChip.PointerPressed += (_, _) => { if (voiceSid != 0) { Act(A_SetSource, sel, 1f); ctx.RequestRebuild(); } else LoadSampleDialog(sampleChip); };
- ToolTip.SetTip(sampleChip, "Load a one-shot sample for this voice (or drop a file on the voice)");
- srcSeg.Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 1, Children = { synthChip, sampleChip } };
- var engBox = new Border { Height = 17, Background = Inset, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(6, 0), VerticalAlignment = VerticalAlignment.Center, Child = new TextBlock { Text = sampleMode ? "Sample" : Engines[sel], FontSize = 9, Foreground = NotaPalette.TextStrong, VerticalAlignment = VerticalAlignment.Center } };
- var voiceHeadRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto"), ColumnSpacing = 8 };
- Grid.SetColumn(voiceHead, 0); Grid.SetColumn(srcSeg, 1); Grid.SetColumn(engBox, 2);
- voiceHeadRow.Children.Add(voiceHead); voiceHeadRow.Children.Add(srcSeg); voiceHeadRow.Children.Add(engBox);
-
- // HIT preview (synth) or WAVE preview (sample).
- var hit = new RhythmHitViz();
- var hitHead = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), Height = 10 };
- hitHead.Children.Add(Sec(sampleMode ? "WAVE" : "HIT"));
- var hitVal = Mono("", sampleMode ? TealB : Brass, 8); hitVal.HorizontalAlignment = HorizontalAlignment.Right; Grid.SetColumn(hitVal, 1); hitHead.Children.Add(hitVal);
- Control hitInner;
- if (sampleMode)
+ else
{
- var wave = new RhythmWaveViz();
- var data = engine.ReadSample(voiceSid);
- wave.SetSamples(data, 1);
- hitVal.Text = "click to replace";
- hitInner = wave;
+ var hv = new RhythmHitView { Width = GraphW };
+ hv.DragBegin = () => { Begin(P("decay")); Begin(P("tune")); };
+ hv.DragEnd = () => { End(P("decay")); End(P("tune")); };
+ hv.Dragged = (dx, dy) => { SetP(P("decay"), G(P("decay")) + (float)(dx * 1.2)); SetP(P("tune"), G(P("tune")) + (float)(dy * 1.2)); Refresh(); };
+ readouts.Add(() =>
+ {
+ float d = G(P("decay")), t = G(P("tune")), pu = G(P("punch"));
+ double dec = RM.DecaySeconds(sel, d, pu), pit = RM.PitchSeconds(sel, t);
+ string cap = pit > 0 ? $"{RM.Ms(pit)} · {RM.Ms(dec)}" : RM.Ms(dec);
+ hv.Set(RM.VoiceNames[sel], dec, pit, RM.DecaySeconds(sel, 1, 0) * 0.8, pu, flashSel, cap);
+ });
+ ToolTip.SetTip(hv, "The hit: amp contour over the pitch drop · drag across for Decay, up / down for Tune (Shift = fine)");
+ AcceptDrops(hv, sel, _ => { });
+ graph = hv;
+ }
+
+ var knobs = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*,*,*,*"), VerticalAlignment = VerticalAlignment.Center };
+ Control[] cells = sampleMode
+ ? new[]
+ {
+ PKnob(P("start"), "START", v => RM.Pct(v), tip: "Where in the file the hit starts"),
+ PKnob(P("length"), "LENGTH", v => RM.Pct(v), tip: "How much of the file plays, from Start"),
+ PKnob(P("tune"), "TUNE", v => RM.Semis(RM.SampleSemis(v)), tip: "Transpose, ±12 semitones"),
+ PKnob(P("decay"), "DECAY", v => RM.Pct(v), tip: "Amp decay — shortens the hit"),
+ PKnob(P("drive"), "DRIVE", v => RM.Pct(v), tip: "Saturation"),
+ PKnob(P("level"), "LEVEL", v => RM.Pct(v), tip: "The voice's level in the kit"),
+ }
+ : new[]
+ {
+ PKnob(P("tune"), "TUNE", v => RM.Pct(v), tip: "Pitch (Kick, Snare, Tom, Hats, Perc) or noise colour (Clap, Rim)"),
+ PKnob(P("decay"), "DECAY", v => RM.Pct(v), tip: "Amp decay"),
+ PKnob(P("punch"), "PUNCH", v => RM.Pct(v), tip: "Attack click / snap"),
+ PKnob(P("tone"), "TONE", v => RM.Pct(v), tip: "Snare body ↔ noise · Hats metal ↔ noise · Perc ring ratio"),
+ PKnob(P("drive"), "DRIVE", v => RM.Pct(v), tip: "Saturation"),
+ PKnob(P("level"), "LEVEL", v => RM.Pct(v), tip: "The voice's level in the kit"),
+ };
+ for (int i = 0; i < cells.Length; i++) { Grid.SetColumn(cells[i], i); knobs.Children.Add(cells[i]); }
+
+ var voiceBody = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 6, Margin = new Thickness(6, 5) };
+ voiceBody.Children.Add(graph);
+ Grid.SetColumn(knobs, 1); voiceBody.Children.Add(knobs);
+ var voice = Section(voiceHeadRow, voiceBody);
+
+ // ---- PERFORM --------------------------------------------------------------------------
+ var perfHead = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), Margin = new Thickness(8, 0) };
+ perfHead.Children.Add(Cap("PERFORM"));
+ var perfSub = Mono("shift+step = accent", NotaPalette.TextDisabled); perfSub.HorizontalAlignment = HorizontalAlignment.Right;
+ Grid.SetColumn(perfSub, 1); perfHead.Children.Add(perfSub);
+
+ var sliders = new StackPanel
+ {
+ Spacing = 6,
+ Children =
+ {
+ Slider("SWING", "swing", "Swing: delays every second 16th — at 100\u2009% by half a step"),
+ Slider("HUMAN", "humanize", "Humanize: a random nudge to every hit's velocity"),
+ Slider("ACCENT", "accent", "How much louder an accented step plays"),
+ },
+ };
+
+ var meter = new MeterBar { Height = 48, Width = MeterScale.StereoWidth, VerticalAlignment = VerticalAlignment.Center };
+ ctx.AddDeviceRefresher(() => { if (engine.TryGetTrackMeter(track, out var m)) meter.Push(m); });
+ var meterScale = new Grid { Height = 48, RowDefinitions = new RowDefinitions(string.Join(",", ScaleRows(0, -12, -48))) };
+ for (int i = 0; i < 3; i++)
+ {
+ var c = Mono(i == 0 ? "0" : i == 1 ? "−12" : "−48", NotaPalette.TextAxis);
+ Grid.SetRow(c, i * 2 + 1); meterScale.Children.Add(c);
}
- else hitInner = hit;
- var hitDock = new DockPanel { LastChildFill = true };
- DockPanel.SetDock(hitHead, Dock.Top); hitDock.Children.Add(hitHead);
- hitDock.Children.Add(new Border { Margin = new Thickness(0, 2, 0, 0), Child = hitInner });
- var hitBox = new Border { Width = 148, Background = Inset, BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Panel, Padding = new Thickness(5, 4), Child = hitDock };
- if (sampleMode) { hitBox.Cursor = new Cursor(StandardCursorType.Hand); hitBox.PointerPressed += (_, _) => LoadSampleDialog(hitBox); }
-
- // engine knobs of the selected voice.
- string P(string p) => $"v{sel}_{p}";
- var knobs = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
- knobs.Children.Add(InstrumentControls.InstKnob(ctx, idx, P("tune"), "TUNE", DoRefresh, 40, 58));
- knobs.Children.Add(InstrumentControls.InstKnob(ctx, idx, P("decay"), "DECAY", DoRefresh, 40, 58));
- knobs.Children.Add(InstrumentControls.InstKnob(ctx, idx, P("punch"), "PUNCH", DoRefresh, 40, 58));
- knobs.Children.Add(InstrumentControls.InstKnob(ctx, idx, P("tone"), "TONE", DoRefresh, 40, 58));
- knobs.Children.Add(InstrumentControls.InstKnob(ctx, idx, P("drive"), "DRIVE", DoRefresh, 40, 58));
- knobs.Children.Add(InstrumentControls.InstKnob(ctx, idx, P("level"), "LEVEL", DoRefresh, 40, 58));
- var voiceMid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 10 };
- Grid.SetColumn(hitBox, 0); Grid.SetColumn(knobs, 1);
- voiceMid.Children.Add(hitBox); voiceMid.Children.Add(knobs);
- var voiceDock = new DockPanel { LastChildFill = true };
- DockPanel.SetDock(voiceHeadRow, Dock.Top); voiceDock.Children.Add(voiceHeadRow);
- voiceDock.Children.Add(new Border { Margin = new Thickness(0, 6, 0, 0), Child = voiceMid });
- var voiceCol = new Border { Padding = new Thickness(10, 7), Child = voiceDock };
-
- // ---- PERFORM column -------------------------------------------------
- var perfKnobs = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
- perfKnobs.Children.Add(InstrumentControls.InstKnob(ctx, idx, "swing", "SWING", DoRefresh, 40, 52, TealB));
- perfKnobs.Children.Add(InstrumentControls.InstKnob(ctx, idx, "humanize", "HUMAN", DoRefresh, 40, 52, TealB));
- perfKnobs.Children.Add(InstrumentControls.InstKnob(ctx, idx, "accent", "ACCENT", DoRefresh, 40, 52));
- var perfDock = new DockPanel { LastChildFill = true };
- var perfHead = Sec("PERFORM"); DockPanel.SetDock(perfHead, Dock.Top); perfDock.Children.Add(perfHead);
- var perfFoot = Mono("shift+step = accent", NotaPalette.TextDisabled, 8); perfFoot.HorizontalAlignment = HorizontalAlignment.Center;
- DockPanel.SetDock(perfFoot, Dock.Bottom); perfDock.Children.Add(perfFoot);
- perfDock.Children.Add(perfKnobs);
- var perfCol = new Border { Width = 170, Background = Panel, BorderBrush = Border2, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(10, 7), Child = perfDock };
-
- var upper = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto") };
- Grid.SetColumn(kitCol, 0); Grid.SetColumn(voiceCol, 1); Grid.SetColumn(perfCol, 2);
- upper.Children.Add(kitCol); upper.Children.Add(voiceCol); upper.Children.Add(perfCol);
-
- // ---- STEP sequencer (bottom) ----------------------------------------
- var stepBtns = new Border[Steps];
- var velFills = new Border[Steps];
- var onArr = new bool[Steps]; var accArr = new bool[Steps]; var velArr = new float[Steps];
- for (int s = 0; s < Steps; s++) { onArr[s] = On(sel, s); accArr[s] = Acc(sel, s); velArr[s] = Vel(sel, s); }
- const double VelH = 11;
-
- void StyleStep(int s)
+ var meterBlock = new Grid
{
- var b = stepBtns[s];
- bool on = onArr[s], acc = accArr[s];
- b.Background = acc && on ? StepAcc : on ? StepOn : StepOff;
- b.BorderBrush = acc && on ? NotaPalette.AccentBright : on ? NotaPalette.AccentHover : Border2;
- b.BorderThickness = new Thickness(1);
+ ColumnDefinitions = new ColumnDefinitions("Auto,Auto"), ColumnSpacing = 4,
+ HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center,
+ };
+ meterBlock.Children.Add(meter);
+ Grid.SetColumn(meterScale, 1); meterBlock.Children.Add(meterScale);
+
+ var master = PKnob("volume", "MASTER", v => RM.Pct(v), 40, 46, "The kit's output level");
+ var glue = PKnob("glue", "GLUE", v => RM.Pct(v), 30, 40, "Glue: a bus compressor on the whole kit — holds the hits together (0 = off)");
+ var perfFoot = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*"), ColumnSpacing = 6 };
+ perfFoot.Children.Add(master);
+ Grid.SetColumn(glue, 1); perfFoot.Children.Add(glue);
+ Grid.SetColumn(meterBlock, 2); perfFoot.Children.Add(meterBlock);
+ var perfFootHost = new Border { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 5, 0, 0), Child = perfFoot };
+
+ var perfBody = new Grid { RowDefinitions = new RowDefinitions("Auto,*"), RowSpacing = 6, Margin = new Thickness(8, 6) };
+ perfBody.Children.Add(sliders);
+ Grid.SetRow(perfFootHost, 1); perfBody.Children.Add(perfFootHost);
+ var perform = Section(perfHead, perfBody);
+ perform.Width = RailW;
+
+ // ---- STEP -----------------------------------------------------------------------------
+ void LoadStrip()
+ {
+ for (int s = 0; s < RM.Steps; s++)
+ {
+ strip.On[s] = pat.On[bank, sel, s]; strip.Acc[s] = pat.Acc[bank, sel, s];
+ strip.Vel[s] = pat.Vel[bank, sel, s];
+ }
+ strip.Changed();
}
- void SyncVel(int s) => velFills[s].Height = VelH * (onArr[s] ? Math.Max(0.12f, velArr[s]) : 0);
+ strip.Commit = s =>
+ {
+ int arg = sel * RM.Steps + s;
+ bool on = strip.On[s], acc = strip.Acc[s];
+ float vel = strip.Vel[s];
+ if (pat.On[bank, sel, s] != on) { Act(RM.A_ToggleStep, arg); pat.On[bank, sel, s] = on; }
+ if (on && Math.Abs(pat.Vel[bank, sel, s] - vel) > 0.5f / 255f) { Act(RM.A_SetVel, arg, vel); pat.Vel[bank, sel, s] = vel; }
+ if (pat.Acc[bank, sel, s] != acc) { Act(RM.A_ToggleAccent, arg); pat.Acc[bank, sel, s] = acc; }
+ ctx.NotifyChanged();
+ Refresh();
+ };
+ void SetSteps(Func<int, (bool On, float Vel, bool Acc)> f)
+ {
+ for (int s = 0; s < RM.Steps; s++)
+ {
+ var (on, vel, acc) = f(s);
+ strip.On[s] = on; strip.Vel[s] = on ? vel : strip.Vel[s]; strip.Acc[s] = on && acc;
+ strip.Commit!(s);
+ }
+ strip.Changed();
+ }
+ strip.StepMenu = s =>
+ {
+ var fly = new MenuFlyout();
+ MenuItem Item(string h, Action a, bool check = false)
+ {
+ var mi = new MenuItem { Header = h };
+ if (check) mi.Icon = new Ellipse { Width = 6, Height = 6, Fill = Brass };
+ mi.Click += (_, _) => a();
+ fly.Items.Add(mi);
+ return mi;
+ }
+ float cur = strip.Vel[s];
+ bool on = strip.On[s];
+ Item($"Step {s + 1} accent", () => { strip.On[s] = true; strip.Acc[s] = !(on && strip.Acc[s]); strip.Vel[s] = Math.Max(cur, RM.NormalVel); strip.Commit!(s); strip.Changed(); }, on && strip.Acc[s]);
+ Item($"Step {s + 1} quiet", () => { strip.On[s] = true; strip.Acc[s] = false; strip.Vel[s] = RM.QuietVel; strip.Commit!(s); strip.Changed(); }, on && !strip.Acc[s] && cur < RM.QuietBelow);
+ var velMenu = new MenuItem { Header = "Velocity" };
+ foreach (var pv in new[] { 1f, 0.75f, 0.5f, 0.25f })
+ {
+ var mi = new MenuItem { Header = RM.Pct(pv) };
+ if (on && Math.Abs(cur - pv) < 0.02f) mi.Icon = new Ellipse { Width = 6, Height = 6, Fill = Brass };
+ mi.Click += (_, _) => { strip.On[s] = true; strip.Vel[s] = pv; strip.Commit!(s); strip.Changed(); };
+ velMenu.Items.Add(mi);
+ }
+ fly.Items.Add(velMenu);
+ fly.Items.Add(new Separator());
+ Item("Fill every beat", () => SetSteps(k => (k % 4 == 0, RM.NormalVel, false)));
+ Item("Fill every 8th", () => SetSteps(k => (k % 2 == 0, RM.NormalVel, false)));
+ Item("Fill every 16th", () => SetSteps(_ => (true, RM.NormalVel, false)));
+ Item("Off-beats", () => SetSteps(k => (k % 4 == 2, RM.NormalVel, false)));
+ fly.Items.Add(new Separator());
+ (bool, float, bool)[] Snap() { var a = new (bool, float, bool)[RM.Steps]; for (int k = 0; k < RM.Steps; k++) a[k] = (strip.On[k], strip.Vel[k], strip.Acc[k]); return a; }
+ Item("Shift left", () => { var a = Snap(); SetSteps(k => a[(k + 1) % RM.Steps]); });
+ Item("Shift right", () => { var a = Snap(); SetSteps(k => a[(k + RM.Steps - 1) % RM.Steps]); });
+ Item("Reverse", () => { var a = Snap(); SetSteps(k => a[RM.Steps - 1 - k]); });
+ fly.Items.Add(new Separator());
+ Item($"Clear {RM.VoiceNames[sel]}", () => SetSteps(k => (false, strip.Vel[k], false)));
+ fly.ShowAt(strip);
+ };
- // Four beat-groups, each four steps; both rows use flex columns so the 16 fill the width.
- var stepsGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*,*"), ColumnSpacing = 9 };
- var velGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*,*"), ColumnSpacing = 9 };
- for (int grp = 0; grp < 4; grp++)
+ // Banks A–D: the playing bank in teal (it is the performance, not a parameter).
+ var bankRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 1 };
+ for (int b = 0; b < RM.Banks; b++)
{
- var gG = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*,*"), ColumnSpacing = 4 };
- var gV = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*,*"), ColumnSpacing = 4 };
- for (int k = 0; k < 4; k++)
+ int bb = b;
+ var tb = new TextBlock { Text = RM.BankNames[b], FontSize = 7, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
+ var cell = new Border { CornerRadius = NotaRadius.Badge, Padding = new Thickness(5, 0), Cursor = new Cursor(StandardCursorType.Hand), Child = tb };
+ ToolTip.SetTip(cell, $"Bank {RM.BankNames[b]} — play and edit this pattern · right-click to copy or clear it");
+ cell.PointerPressed += (_, e) =>
{
- int s = grp * 4 + k;
- var beat = new TextBlock { Text = (s % 4 == 0) ? (s + 1).ToString() : "", FontSize = 7, Foreground = Muted, Margin = new Thickness(4, 3, 0, 0), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top, IsHitTestVisible = false };
- var btn = new Border { Height = 24, CornerRadius = NotaRadius.Tile, Child = beat, Cursor = new Cursor(StandardCursorType.Hand) };
- stepBtns[s] = btn; StyleStep(s);
- int ss = s;
- btn.PointerPressed += (_, e) =>
- {
- bool shift = (e.KeyModifiers & KeyModifiers.Shift) != 0;
- if (shift) { Act(A_ToggleAccent, sel * Steps + ss); accArr[ss] = !accArr[ss]; if (accArr[ss] && !onArr[ss]) { Act(A_ToggleStep, sel * Steps + ss); onArr[ss] = true; } }
- else { Act(A_ToggleStep, sel * Steps + ss); onArr[ss] = !onArr[ss]; if (onArr[ss] && velArr[ss] <= 0) velArr[ss] = 0.7f; }
- StyleStep(ss); SyncVel(ss);
- };
- Grid.SetColumn(btn, k); gG.Children.Add(btn);
-
- var fill = new Border { VerticalAlignment = VerticalAlignment.Bottom, Background = VelFill, CornerRadius = NotaRadius.Clip };
- velFills[s] = fill; SyncVel(s);
- var vb = new Border { Background = NotaPalette.SurfaceAbyss, CornerRadius = NotaRadius.Clip, Child = fill, Cursor = new Cursor(StandardCursorType.SizeNorthSouth), ClipToBounds = true };
- void SetVelFromY(PointerEventArgs pe)
- {
- double h = Math.Max(1, vb.Bounds.Height);
- float nv = (float)Math.Clamp(1.0 - pe.GetPosition(vb).Y / h, 0.0, 1.0);
- velArr[ss] = nv; Act(A_SetVel, sel * Steps + ss, nv);
- if (!onArr[ss]) { Act(A_ToggleStep, sel * Steps + ss); onArr[ss] = true; StyleStep(ss); }
- SyncVel(ss);
- }
- vb.PointerPressed += (_, e) => { e.Pointer.Capture(vb); SetVelFromY(e); };
- vb.PointerMoved += (_, e) => { if (e.GetCurrentPoint(vb).Properties.IsLeftButtonPressed) SetVelFromY(e); };
- vb.PointerReleased += (_, e) => e.Pointer.Capture(null);
- Grid.SetColumn(vb, k); gV.Children.Add(vb);
+ var pt = e.GetCurrentPoint(cell);
+ e.Handled = true;
+ if (pt.Properties.IsRightButtonPressed) { BankMenu(bb, cell); return; }
+ if (!pt.Properties.IsLeftButtonPressed || bb == bank) return;
+ Act(RM.A_SelectBank, bb); ctx.NotifyChanged(); ReloadPattern();
+ };
+ bankCells[b] = cell; bankTexts[b] = tb; bankRow.Children.Add(cell);
+ }
+ void PaintBanks()
+ {
+ for (int b = 0; b < RM.Banks; b++)
+ {
+ bool on = b == bank;
+ bankCells[b].Background = on ? Teal : Brushes.Transparent;
+ bankTexts[b].Foreground = on ? OnAccent : TextTertiary;
+ bankTexts[b].FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
}
- Grid.SetColumn(gG, grp); stepsGrid.Children.Add(gG);
- Grid.SetColumn(gV, grp); velGrid.Children.Add(gV);
}
- velGrid.Height = VelH;
-
- var stepHead = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 };
- stepHead.Children.Add(new TextBlock { Text = "STEP — ", FontSize = 8, FontWeight = FontWeight.Bold, Foreground = Muted, VerticalAlignment = VerticalAlignment.Center });
- stepHead.Children.Add(new TextBlock { Text = Names[sel], FontSize = 8, FontWeight = FontWeight.Bold, Foreground = TextPrimary, VerticalAlignment = VerticalAlignment.Center });
- // bank chips A B C D
- var banks = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 1, Margin = new Thickness(8, 0, 0, 0) };
- for (int b = 0; b < 4; b++)
+ void BankMenu(int b, Control anchor)
{
- int bb = b; bool cur = b == bank;
- var chip = new Border { CornerRadius = NotaRadius.Badge, Padding = new Thickness(6, 1), Cursor = new Cursor(StandardCursorType.Hand), Background = cur ? TealB : Brushes.Transparent, Child = new TextBlock { Text = ((char)('A' + b)).ToString(), FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = cur ? NotaPalette.TextOnAccent : Muted } };
- chip.PointerPressed += (_, _) => { Act(A_SelectBank, bb); ctx.RequestRebuild(); };
- banks.Children.Add(chip);
+ var fly = new MenuFlyout();
+ var copy = new MenuItem { Header = $"Copy {RM.BankNames[b]} to" };
+ for (int d = 0; d < RM.Banks; d++)
+ {
+ if (d == b) continue;
+ int dd = d;
+ var mi = new MenuItem { Header = $"Bank {RM.BankNames[d]}" };
+ mi.Click += (_, _) => { Act(RM.A_CopyBank, b * RM.Banks + dd); ctx.NotifyChanged(); ReloadPattern(); };
+ copy.Items.Add(mi);
+ }
+ fly.Items.Add(copy);
+ var clear = new MenuItem { Header = $"Clear bank {RM.BankNames[b]}" };
+ clear.Click += (_, _) => { Act(RM.A_ClearBank, b); ctx.NotifyChanged(); ReloadPattern(); };
+ fly.Items.Add(clear);
+ fly.ShowAt(anchor);
}
- stepHead.Children.Add(banks);
- var playText = Mono("step –", TealB, 8); playText.HorizontalAlignment = HorizontalAlignment.Right;
- var stepHeadRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*") };
- stepHeadRow.Children.Add(stepHead); Grid.SetColumn(playText, 1); stepHeadRow.Children.Add(playText);
-
- var seqInner = new StackPanel { Spacing = 4, Children = { stepHeadRow, stepsGrid, velGrid } };
- var seqCol = new Border { Height = 78, Background = SeqBg, BorderBrush = Border2, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(10, 6), Child = seqInner };
-
- // ---- assemble body --------------------------------------------------
- var body = new DockPanel { LastChildFill = true, Background = NotaPalette.BgApp };
- DockPanel.SetDock(seqCol, Dock.Bottom); body.Children.Add(seqCol);
- body.Children.Add(upper);
-
- // ---- live follow ----------------------------------------------------
- int lastHead = -1;
- var scope = new float[16];
- void DoRefresh()
+ var bankBox = new Border
{
- if (!sampleMode) { hit.Set(G(P("decay")), G(P("tune")), G(P("punch")), 0); hitVal.Text = Names[sel]; }
+ Background = NotaPalette.BgSunken, BorderBrush = BorderDef, BorderThickness = new Thickness(1),
+ CornerRadius = NotaRadius.Control, Padding = new Thickness(1), VerticalAlignment = VerticalAlignment.Center, Child = bankRow,
+ };
+
+ var stepCount = Mono("", TextTertiary);
+ stepCount.HorizontalAlignment = HorizontalAlignment.Right;
+ readouts.Add(() => stepCount.Text = $"{pat.Count(bank, sel)} of {RM.Steps} · 1/16 · bank {RM.BankNames[bank]}");
+ var stepHead = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,*"), ColumnSpacing = 6, Height = 12 };
+ stepHead.Children.Add(Cap("STEP"));
+ var stepName = new TextBlock { Text = RM.VoiceNames[sel], FontSize = 8, FontWeight = FontWeight.SemiBold, Foreground = TextPrimary, VerticalAlignment = VerticalAlignment.Center };
+ Grid.SetColumn(stepName, 1); stepHead.Children.Add(stepName);
+ Grid.SetColumn(bankBox, 2); stepHead.Children.Add(bankBox);
+ Grid.SetColumn(stepCount, 3); stepHead.Children.Add(stepCount);
+ var stepGrid = new Grid { RowDefinitions = new RowDefinitions("Auto,*"), RowSpacing = 3, Margin = new Thickness(6, 4) };
+ stepGrid.Children.Add(stepHead);
+ Grid.SetRow(strip, 1); stepGrid.Children.Add(strip);
+ var steps = SectionBox(stepGrid);
+ steps.Height = StepH;
+
+ void ReloadPattern()
+ {
+ pat = RM.Parse(engine.GetPluginState(track, -1), pc);
+ if (pat.SelectedVoice != sel) { ctx.RequestRebuild(); return; }
+ bank = pat.CurrentBank;
+ LoadStrip(); PaintBanks(); Refresh();
}
- void Refresh()
+
+ // ---- status ----------------------------------------------------------------------------
+ readouts.Add(() => status.Text = RM.Summary(G, pat, sel, sampleMode, sampleName));
+ var statusBar = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 10 };
+ statusBar.Children.Add(status);
+ Grid.SetColumn(meta, 1); statusBar.Children.Add(meta);
+ var statusHost = new Border
+ {
+ Height = StatusH, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 1, 0, 0),
+ Background = NotaPalette.SurfaceAbyss, Padding = new Thickness(8, 0), Child = statusBar,
+ };
+
+ // ---- live ------------------------------------------------------------------------------
+ void Live()
{
int n = engine.InstrumentScope(track, scope);
- int head = n > 0 ? (int)Math.Round(scope[0]) : -1;
- if (head != lastHead)
+ if (n >= RM.ScopeLength)
{
- if (lastHead >= 0 && lastHead < Steps) StyleStep(lastHead);
- if (head >= 0 && head < Steps) { stepBtns[head].BorderBrush = TealBright; } // colour only: a state never thickens a border
- lastHead = head;
- playText.Text = head >= 0 ? $"step {head + 1} / 16" : "step –";
+ int rev = (int)scope[RM.S_Rev];
+ if (lastRev >= 0 && rev != lastRev) ReloadPattern();
+ lastRev = rev;
+ int head = (int)Math.Round(scope[RM.S_Step]);
+ strip.SetHead(head);
+ for (int v = 0; v < RM.Voices; v++)
+ kitDots[v].Fill = scope[RM.S_Flash0 + v] > 0.1f ? Hue(v) : NotaPalette.Wash(NotaPalette.Ink(Dots[v]), 0x8C);
+ float f = scope[RM.S_Flash0 + sel], p = scope[RM.S_Pos0 + sel];
+ if (Math.Abs(f - flashSel) > 0.05f || Math.Abs(p - posSel) > 0.002f) { flashSel = f; posSel = p; Refresh(); }
}
- float flash = (n > 1 + sel) ? scope[1 + sel] : 0f;
- if (!sampleMode) hit.Set(G(P("decay")), G(P("tune")), G(P("punch")), flash);
- // kit dot flashes
- // A voice that just fired lights its dot at full hue; otherwise the dot rests one step
- // down. Discrete, not an opacity ramp (almanac: no opacity for state, no meter easing).
- for (int v = 0; v < Voices && 1 + v < n; v++) kitDots[v].Fill = scope[1 + v] > 0.1f ? NotaPalette.Ink(Dots[v]) : NotaPalette.Wash(NotaPalette.Ink(Dots[v]), 0x8C);
+ int voices = Math.Max(0, engine.InstrumentVoiceCount(track));
+ double sr = engine.SampleRate > 0 ? engine.SampleRate : 48000;
+ meta.Text = $"{voices}/{RM.Voices} voices · {NotaNum.Unit(sr / 1000, "0.#", "kHz")} · {NotaNum.Bpm(engine.Bpm)} BPM · CPU {NotaNum.Unit(engine.CpuLoad * 100, "0.0", "%")}";
}
+
+ // ---- assembly --------------------------------------------------------------------------
+ var top = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = NotaSpace.DeviceGap };
+ top.Children.Add(kit);
+ Grid.SetColumn(voice, 1); top.Children.Add(voice);
+ Grid.SetColumn(perform, 2); top.Children.Add(perform);
+ var body = new Grid { RowDefinitions = new RowDefinitions("*,Auto"), RowSpacing = NotaSpace.DeviceGap, Margin = new Thickness(NotaSpace.DeviceGap) };
+ body.Children.Add(top);
+ Grid.SetRow(steps, 1); body.Children.Add(steps);
+
+ DockPanel.SetDock(statusHost, Dock.Bottom);
+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.Gutter, Children = { statusHost, body } };
+
+ LoadStrip(); PaintBanks();
+ ctx.AddDeviceRefresher(Live);
ctx.SetInstLiveViz(Refresh);
- DoRefresh();
- return body;
+ Refresh();
+ Live();
+ return root;
+ }
+
+ // A section: card ground, hairline, radius 6, with an 18px header strip.
+ private static Border Section(Control head, Control body)
+ {
+ var headHost = new Border { Height = HeadH, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Child = head };
+ var g = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
+ g.Children.Add(headHost);
+ Grid.SetRow(body, 1); g.Children.Add(body);
+ return SectionBox(g);
+ }
+
+ private static Border SectionBox(Control child) => new()
+ {
+ Background = NotaPalette.SurfaceCard, BorderBrush = BorderDef, BorderThickness = new Thickness(1),
+ CornerRadius = NotaRadius.Tile, ClipToBounds = true, Child = child,
+ };
+
+ /// <summary>Row definitions that put a caption for each dB mark at its place on the meter.</summary>
+ private static IEnumerable<string> ScaleRows(params double[] dbs)
+ {
+ double prev = 0;
+ foreach (var db in dbs)
+ {
+ double fromTop = 1.0 - MeterScale.NormDb(db);
+ yield return Math.Max(0, fromTop - prev).ToString("0.000", NotaNum.Culture) + "*";
+ yield return "Auto";
+ prev = fromTop;
+ }
+ yield return Math.Max(0, 1.0 - prev).ToString("0.000", NotaNum.Culture) + "*";
}
}
diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.cs
index 6111ed18..43dc8531 100644
--- a/src/managed/Nota.App/PreferencesWindow.cs
+++ b/src/managed/Nota.App/PreferencesWindow.cs
@@ -628,6 +628,8 @@ public sealed class PreferencesWindow : NotaWindow
("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"),
+ ("Click · ⇧ · ⌥ a Rhythm step", "Step on / off · accent · quiet step — drag across to paint, up / down (or scroll) for its velocity"),
+ ("Click a Rhythm voice", "Select and play it · drop a file on it to load a sample"),
}),
};
diff --git a/src/managed/Nota.Application/Instruments/RhythmModel.cs b/src/managed/Nota.Application/Instruments/RhythmModel.cs
new file mode 100644
index 00000000..703fe58a
--- /dev/null
+++ b/src/managed/Nota.Application/Instruments/RhythmModel.cs
@@ -0,0 +1,178 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Rhythm (built-in instrument kind 12) — the engine's own value maps, in one place for
+// the editor card and the MCP server: the kit (names, engines, MIDI map), param ids, the
+// action ids of the pattern channel, the state-blob layout (params, then the four banks of
+// steps), the scope telemetry, what a normalized knob means in seconds / hertz / semitones,
+// a one-line summary and a guide to every parameter. Mirrors RhythmMachine.h.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Text;
+
+namespace Nota.Application;
+
+public static class RhythmModel
+{
+ public const int Kind = 12;
+ public const int Voices = 8, Steps = 16, Banks = 4;
+
+ // RhythmMachine::Act.
+ public const int A_ToggleStep = 0, A_SetVel = 1, A_ToggleAccent = 2, A_SelectBank = 3, A_ClearBank = 4,
+ A_SelectVoice = 5, A_SetSource = 6, A_CopyBank = 7, A_Audition = 8, A_ClearVoice = 9;
+
+ // RhythmMachine::Scope.
+ public const int S_Step = 0, S_Bank = 1, S_Rev = 2, S_Active = 3, S_Glue = 4, S_Flash0 = 5, S_Pos0 = S_Flash0 + Voices,
+ ScopeLength = S_Pos0 + Voices;
+
+ // State magics: RTH1 carries the first 60 params, RTH2 all of them.
+ private const uint MagicV1 = 0x31485452, MagicV2 = 0x32485452;
+ public const int LegacyParams = Voices * 7 + 4;
+
+ public static readonly string[] VoiceNames = { "Kick", "Snare", "Clap", "Rim", "Closed Hat", "Open Hat", "Tom", "Perc" };
+ public static readonly string[] ShortNames = { "KICK", "SNR", "CLAP", "RIM", "CH", "OH", "TOM", "PERC" };
+ /// <summary>The synth engine each voice runs (lower-case, as the status line prints it).</summary>
+ public static readonly string[] Engines = { "analog", "noise", "clap", "rim", "metal", "metal", "analog", "ring" };
+ /// <summary>The MIDI note that plays each voice live (GM drum map).</summary>
+ public static readonly int[] MidiNotes = { 36, 38, 39, 37, 42, 46, 45, 41 };
+ public static readonly string[] BankNames = { "A", "B", "C", "D" };
+
+ /// <summary>A step below this velocity (and not accented) is a quiet step.</summary>
+ public const float QuietBelow = 0.45f;
+ public const float QuietVel = 0.3f, NormalVel = 0.7f;
+
+ public static string Id(int voice, string p) => $"v{voice}_{p}";
+ public static readonly string[] VoiceParams = { "tune", "decay", "punch", "tone", "drive", "level", "pan", "start", "length", "reverse" };
+ public static readonly string[] GlobalParams = { "swing", "humanize", "accent", "volume", "glue" };
+
+ public static double ExpMap(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0.0, 1.0));
+
+ // ---- what a knob means ---------------------------------------------------------------
+
+ /// <summary>The amp decay (to −60 dB) of a synth voice, in seconds.</summary>
+ public static double DecaySeconds(int voice, float decay, float punch = 0.5f) => voice switch
+ {
+ 0 or 6 => ExpMap(decay, 0.06, 1.2),
+ 1 => ExpMap(decay, 0.05, 0.5) * (0.4 + 0.6 * (1.0 - punch)),
+ 2 => ExpMap(decay, 0.05, 0.4),
+ 3 => ExpMap(decay, 0.02, 0.12),
+ 4 => ExpMap(decay, 0.02, 0.16),
+ 5 => ExpMap(decay, 0.08, 0.7),
+ _ => ExpMap(decay, 0.05, 0.6),
+ };
+ /// <summary>A sample voice's amp decay, in seconds.</summary>
+ public static double SampleDecaySeconds(float decay) => ExpMap(decay, 0.05, 2.0);
+ /// <summary>The pitch drop of the Kick / Tom (to −60 dB), in seconds; 0 for voices without one.</summary>
+ public static double PitchSeconds(int voice, float tune) => voice is 0 or 6 ? 0.03 + 0.05 * tune : 0;
+ /// <summary>The voice's base frequency (or its noise colour), in Hz.</summary>
+ public static double TuneHz(int voice, float tune) => voice switch
+ {
+ 0 => ExpMap(tune, 30, 120),
+ 6 => ExpMap(tune, 80, 300),
+ 1 => ExpMap(tune, 140, 330),
+ 2 => ExpMap(tune, 700, 1800),
+ 3 => ExpMap(tune, 900, 2600),
+ 4 or 5 => ExpMap(tune, 320, 900),
+ _ => ExpMap(tune, 200, 1200),
+ };
+ /// <summary>A sample voice's transpose, −12 … +12 semitones.</summary>
+ public static double SampleSemis(float tune) => (tune - 0.5) * 24.0;
+ public static float SampleSemisNorm(double st) => (float)Math.Clamp(0.5 + st / 24.0, 0, 1);
+ /// <summary>The sample region's end, 0..1 of the file.</summary>
+ public static double RegionEnd(float start, float length) => Math.Min(1.0, start + length);
+
+ // ---- the state blob -------------------------------------------------------------------
+
+ /// <summary>The pattern part of a Rhythm state blob (plus the bank / voice the editor shows).</summary>
+ public sealed class Pattern
+ {
+ public int CurrentBank, SelectedVoice;
+ public readonly bool[,,] On = new bool[Banks, Voices, Steps];
+ public readonly float[,,] Vel = new float[Banks, Voices, Steps];
+ public readonly bool[,,] Acc = new bool[Banks, Voices, Steps];
+
+ public bool Quiet(int b, int v, int s) => On[b, v, s] && !Acc[b, v, s] && Vel[b, v, s] < QuietBelow;
+ public int Count(int b, int v) { int n = 0; for (int s = 0; s < Steps; s++) if (On[b, v, s]) n++; return n; }
+ }
+
+ /// <summary>Read the blob: [magic][params][bank, voice, 2][on, vel, acc per bank/voice/step].
+ /// <paramref name="paramCount"/> is the instrument's current count (RTH2); an RTH1 blob holds 60.</summary>
+ public static Pattern Parse(byte[] st, int paramCount)
+ {
+ var p = new Pattern();
+ if (st.Length < 4) return p;
+ uint magic = BitConverter.ToUInt32(st, 0);
+ int n = magic == MagicV1 ? LegacyParams : magic == MagicV2 ? paramCount : -1;
+ if (n < 0) return p;
+ int off = 4 + n * 4;
+ if (off + 2 <= st.Length) { p.CurrentBank = Math.Min((int)st[off], Banks - 1); p.SelectedVoice = Math.Min((int)st[off + 1], Voices - 1); }
+ off += 4;
+ for (int b = 0; b < Banks; b++)
+ for (int v = 0; v < Voices; v++)
+ for (int s = 0; s < Steps; s++, off += 3)
+ {
+ if (off + 3 > st.Length) return p;
+ p.On[b, v, s] = st[off] != 0; p.Vel[b, v, s] = st[off + 1] / 255f; p.Acc[b, v, s] = st[off + 2] != 0;
+ }
+ return p;
+ }
+
+ // ---- words ------------------------------------------------------------------------------
+
+ private static string S(double v, string f) => v.ToString(f, CultureInfo.InvariantCulture);
+ public static string Pct(double v) => S(v * 100, "0") + "\u2009%";
+ public static string Ms(double s) => s < 0.9995 ? S(s * 1000, "0") + "\u2009ms" : S(s, "0.00") + "\u2009s";
+ public static string Semis(double st) => S(Math.Round(st), "+0;\u22120;0") + "\u2009st";
+
+ /// <summary>The steps of a voice as the status line lists them: "1 · 5 · 9 accent · 13 quiet".</summary>
+ public static string StepList(Pattern p, int bank, int v)
+ {
+ var parts = new List<string>();
+ for (int s = 0; s < Steps; s++)
+ {
+ if (!p.On[bank, v, s]) continue;
+ string t = (s + 1).ToString(CultureInfo.InvariantCulture);
+ if (p.Acc[bank, v, s]) t += " accent";
+ else if (p.Quiet(bank, v, s)) t += " quiet";
+ parts.Add(t);
+ }
+ return parts.Count == 0 ? "no steps" : "steps " + string.Join(" · ", parts);
+ }
+
+ /// <summary>One line about the selected voice and the groove.</summary>
+ public static string Summary(Func<string, float> g, Pattern p, int voice, bool sample, string sampleName)
+ {
+ int v = Math.Clamp(voice, 0, Voices - 1);
+ var sb = new StringBuilder(VoiceNames[v]);
+ float F(string id) => g(Id(v, id));
+ if (sample)
+ {
+ sb.Append(" · sample ").Append(sampleName.Length > 0 ? sampleName : "—")
+ .Append(" · ").Append(Pct(F("start"))).Append(" → ").Append(Pct(RegionEnd(F("start"), F("length"))));
+ if (F("reverse") >= 0.5f) sb.Append(" reversed");
+ sb.Append(" · tune ").Append(Semis(SampleSemis(F("tune"))));
+ }
+ else
+ sb.Append(" · synth ").Append(Engines[v]).Append(" · tune ").Append(Pct(F("tune")))
+ .Append(" · decay ").Append(Pct(F("decay")));
+ sb.Append(" · level ").Append(Pct(F("level")));
+ if (g("swing") > 0.005f) sb.Append(" · swing ").Append(Pct(g("swing")));
+ if (g("humanize") > 0.005f) sb.Append(" · human ").Append(Pct(g("humanize")));
+ if (g("glue") > 0.005f) sb.Append(" · glue ").Append(Pct(g("glue")));
+ sb.Append(" · ").Append(StepList(p, p.CurrentBank, v));
+ return sb.ToString();
+ }
+
+ public const string Guide =
+ "Voices 0..7: Kick, Snare, Clap, Rim, Closed Hat, Open Hat, Tom, Perc (MIDI 36, 38, 39, 37, 42, 46, 45, 41 play them live). "
+ + "Per-voice param ids v{n}_{p}, all 0..1: tune (synth: pitch or noise colour; sample: .5 = original, ±12 st at 0/1), "
+ + "decay (amp decay; Kick 60 ms..1.2 s, Snare 50..500 ms, Closed Hat 20..160 ms, Open Hat 80..700 ms; sample 50 ms..2 s), "
+ + "punch (attack click / snap), tone (Snare body↔noise, Hats metal↔noise, sample low-pass), drive (saturation), "
+ + "level, pan (.5 = centre), start / length (the sample region, fractions of the file; end = start + length), "
+ + "reverse (≥ .5 plays the region backwards). Globals: swing (delays odd 16ths, 1 = half a step), humanize (velocity "
+ + "jitter), accent (how much louder an accented step plays, up to 2×), glue (bus compressor: 0 off … 1 heavy), "
+ + "volume (master). Steps: 16 per bar at 1/16 in four banks A–D; a step has a velocity 0..1 (below 0.45 it is a quiet "
+ + "step) and an accent flag. Closed Hat chokes Open Hat.";
+}
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
index ae446bc4..85e68adf 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
@@ -674,7 +674,12 @@ public sealed partial class NotaEngine
{ ThrowIfDisposed(); return NativeMethods.TrackGrainInfo(_handle, trackId, out info) != 0; }
public bool SetRhythmVoiceSample(int trackId, int voice, string path)
- { ThrowIfDisposed(); return NativeMethods.RhythmSetVoiceSample(_handle, trackId, voice, path) != 0; }
+ {
+ ThrowIfDisposed();
+ bool ok = NativeMethods.RhythmSetVoiceSample(_handle, trackId, voice, path) != 0;
+ if (ok && TryGetRhythmVoiceInfo(trackId, voice, out var vi)) RememberSampleName(vi.SampleId, path);
+ return ok;
+ }
public bool TryGetRhythmVoiceInfo(int trackId, int voice, out NotaSamplerInfo info)
{ ThrowIfDisposed(); return NativeMethods.RhythmVoiceInfo(_handle, trackId, voice, out info) != 0; }
public int RhythmVoiceSource(int trackId, int voice)
diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
index ddb34867..2ad617d0 100644
--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
@@ -770,34 +770,133 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
Inst("flux", 11, "Vector Dance", ("vecx", 0.50f), ("vecy", 0.50f), ("age", 0.20f), ("motion", 0.60f), ("motrate", 0.6f), ("filter", 0.60f), ("env", 0.60f), ("space", 0.35f), ("listen", 0.90f), ("target", 1f));
Inst("flux", 11, "Pitch Wobble", ("vecx", 0.20f), ("vecy", 0.50f), ("age", 0.30f), ("motion", 0.30f), ("filter", 0.55f), ("env", 0.55f), ("space", 0.30f), ("listen", 0.70f), ("target", 1f / 3f));
- // ---- Nota Rhythm (kind 12) — drum-machine kit voicings. Voices: 0 Kick, 1 Snare,
+ // ---- Nota Rhythm (kind 12) — drum-machine kits (the sound, not the pattern: applying a
+ // kit keeps the steps and each voice's sample region). Voices: 0 Kick, 1 Snare,
// 2 Clap, 3 Rim, 4 Closed Hat, 5 Open Hat, 6 Tom, 7 Perc. Param id "v{n}_{p}"
- // (tune/decay/punch/tone/drive/level) + globals swing/humanize/accent.
+ // (tune/decay/punch/tone/drive/level/pan) + globals swing/humanize/accent/volume/glue.
+ // Decay spans per voice: Kick .06–1.2 s, Snare .05–.5 s, Closed Hat .02–.16 s,
+ // Open Hat .08–.7 s; pan .5 = centre; glue 0 = off.
+ // Classic machines
Inst("drums", 12, "808 Kit",
("v0_tune", 0.16f), ("v0_decay", 0.72f), ("v0_drive", 0.18f),
("v1_tune", 0.35f), ("v1_decay", 0.4f), ("v1_tone", 0.45f),
("v2_decay", 0.42f), ("v4_decay", 0.12f), ("v5_decay", 0.55f),
- ("swing", 0f), ("accent", 0.7f));
+ ("swing", 0f), ("accent", 0.7f), ("glue", 0.15f));
Inst("drums", 12, "909 Kit",
("v0_tune", 0.3f), ("v0_decay", 0.5f), ("v0_punch", 0.7f), ("v0_drive", 0.3f),
("v1_tune", 0.5f), ("v1_decay", 0.35f), ("v1_tone", 0.6f),
- ("v4_decay", 0.14f), ("v5_decay", 0.45f), ("swing", 0.08f), ("accent", 0.75f));
- Inst("drums", 12, "Trap",
- ("v0_tune", 0.1f), ("v0_decay", 0.85f), ("v0_drive", 0.35f),
- ("v1_tune", 0.4f), ("v1_decay", 0.3f), ("v4_decay", 0.08f), ("v5_decay", 0.6f),
- ("swing", 0.12f), ("accent", 0.85f));
+ ("v4_decay", 0.14f), ("v5_decay", 0.45f), ("swing", 0.08f), ("accent", 0.75f), ("glue", 0.2f));
+ Inst("drums", 12, "Deep 808 Sub",
+ ("v0_tune", 0.08f), ("v0_decay", 0.95f), ("v0_punch", 0.35f), ("v0_drive", 0.12f), ("v0_level", 0.9f),
+ ("v1_tune", 0.3f), ("v1_decay", 0.45f), ("v1_tone", 0.4f), ("v2_decay", 0.5f),
+ ("v4_decay", 0.1f), ("v4_level", 0.65f), ("v5_decay", 0.6f), ("v5_level", 0.6f), ("glue", 0.1f));
+ Inst("drums", 12, "Tight & Dry",
+ ("v0_decay", 0.3f), ("v0_punch", 0.65f), ("v1_decay", 0.2f), ("v1_punch", 0.6f), ("v2_decay", 0.2f),
+ ("v3_decay", 0.3f), ("v4_decay", 0.05f), ("v5_decay", 0.25f), ("v6_decay", 0.3f), ("v7_decay", 0.2f),
+ ("v0_drive", 0.1f), ("v1_drive", 0.1f), ("glue", 0.2f));
+ Inst("drums", 12, "Wide Stereo",
+ ("v0_tune", 0.22f), ("v0_decay", 0.55f), ("v3_pan", 0.62f), ("v2_pan", 0.42f),
+ ("v4_pan", 0.34f), ("v4_decay", 0.13f), ("v5_pan", 0.68f), ("v5_decay", 0.5f),
+ ("v6_pan", 0.28f), ("v7_pan", 0.74f), ("v7_decay", 0.35f), ("glue", 0.2f));
+ // House · techno · electro
Inst("drums", 12, "House",
("v0_tune", 0.28f), ("v0_decay", 0.45f), ("v0_punch", 0.6f),
("v2_decay", 0.35f), ("v4_decay", 0.16f), ("v5_decay", 0.4f),
- ("swing", 0.18f), ("accent", 0.6f));
- Inst("drums", 12, "Lo-Fi",
- ("v0_tune", 0.2f), ("v0_decay", 0.55f), ("v0_tone", 0.3f), ("v0_drive", 0.45f),
- ("v1_tune", 0.32f), ("v1_decay", 0.42f), ("v1_tone", 0.35f),
- ("v4_decay", 0.14f), ("swing", 0.22f), ("humanize", 0.3f), ("accent", 0.5f));
+ ("swing", 0.18f), ("accent", 0.6f), ("glue", 0.25f));
Inst("drums", 12, "Techno",
("v0_tune", 0.24f), ("v0_decay", 0.5f), ("v0_punch", 0.7f), ("v0_drive", 0.4f),
("v4_decay", 0.1f), ("v5_decay", 0.5f), ("v7_tune", 0.5f), ("v7_decay", 0.4f),
- ("swing", 0f), ("accent", 0.8f));
+ ("swing", 0f), ("accent", 0.8f), ("glue", 0.3f));
+ Inst("drums", 12, "Dub Techno",
+ ("v0_tune", 0.2f), ("v0_decay", 0.62f), ("v0_tone", 0.3f), ("v0_drive", 0.2f),
+ ("v3_tune", 0.3f), ("v3_decay", 0.75f), ("v3_level", 0.7f),
+ ("v4_decay", 0.12f), ("v4_tone", 0.4f), ("v5_decay", 0.75f), ("v5_level", 0.55f),
+ ("v7_tune", 0.35f), ("v7_decay", 0.6f), ("v7_level", 0.55f), ("glue", 0.3f));
+ Inst("drums", 12, "Minimal Click",
+ ("v0_tune", 0.3f), ("v0_decay", 0.3f), ("v0_punch", 0.85f), ("v0_drive", 0.05f),
+ ("v3_tune", 0.7f), ("v3_decay", 0.25f), ("v4_decay", 0.06f), ("v4_tone", 0.7f),
+ ("v7_tune", 0.72f), ("v7_decay", 0.2f), ("v7_tone", 0.8f), ("swing", 0.06f), ("glue", 0.15f));
+ Inst("drums", 12, "Big Room",
+ ("v0_tune", 0.26f), ("v0_decay", 0.5f), ("v0_punch", 0.9f), ("v0_drive", 0.5f), ("v0_level", 0.9f),
+ ("v1_decay", 0.5f), ("v1_tone", 0.6f), ("v2_decay", 0.62f), ("v2_level", 0.9f),
+ ("v5_decay", 0.35f), ("accent", 0.85f), ("glue", 0.5f));
+ Inst("drums", 12, "Electro Funk",
+ ("v0_tune", 0.2f), ("v0_decay", 0.6f), ("v0_drive", 0.25f), ("v1_tune", 0.42f), ("v1_decay", 0.35f),
+ ("v2_decay", 0.5f), ("v6_tune", 0.5f), ("v6_decay", 0.5f), ("v4_decay", 0.1f),
+ ("swing", 0.2f), ("accent", 0.7f), ("glue", 0.2f));
+ Inst("drums", 12, "Acid Rave",
+ ("v0_tune", 0.32f), ("v0_decay", 0.45f), ("v0_punch", 0.75f), ("v0_drive", 0.45f),
+ ("v1_tune", 0.55f), ("v1_tone", 0.65f), ("v1_drive", 0.35f),
+ ("v4_decay", 0.12f), ("v4_tone", 0.7f), ("v5_decay", 0.5f), ("v5_tone", 0.65f), ("glue", 0.35f));
+ Inst("drums", 12, "Industrial",
+ ("v0_tune", 0.2f), ("v0_decay", 0.5f), ("v0_punch", 0.9f), ("v0_drive", 0.85f),
+ ("v1_tune", 0.35f), ("v1_tone", 0.75f), ("v1_drive", 0.75f), ("v2_drive", 0.6f),
+ ("v3_drive", 0.7f), ("v4_drive", 0.5f), ("v7_drive", 0.8f), ("v7_tone", 0.9f),
+ ("accent", 0.9f), ("glue", 0.7f), ("volume", 0.72f));
+ Inst("drums", 12, "Synthwave",
+ ("v0_tune", 0.3f), ("v0_decay", 0.5f), ("v1_tune", 0.4f), ("v1_decay", 0.75f), ("v1_tone", 0.45f),
+ ("v1_punch", 0.3f), ("v2_decay", 0.6f), ("v6_tune", 0.35f), ("v6_decay", 0.62f),
+ ("v5_decay", 0.45f), ("glue", 0.3f));
+ // Hip-hop · breaks
+ Inst("drums", 12, "Trap",
+ ("v0_tune", 0.1f), ("v0_decay", 0.85f), ("v0_drive", 0.35f),
+ ("v1_tune", 0.4f), ("v1_decay", 0.3f), ("v4_decay", 0.08f), ("v5_decay", 0.6f),
+ ("swing", 0.12f), ("accent", 0.85f), ("glue", 0.2f));
+ Inst("drums", 12, "Lo-Fi",
+ ("v0_tune", 0.2f), ("v0_decay", 0.55f), ("v0_tone", 0.3f), ("v0_drive", 0.45f),
+ ("v1_tune", 0.32f), ("v1_decay", 0.42f), ("v1_tone", 0.35f),
+ ("v4_decay", 0.14f), ("swing", 0.22f), ("humanize", 0.3f), ("accent", 0.5f), ("glue", 0.25f));
+ Inst("drums", 12, "Boom Bap",
+ ("v0_tune", 0.25f), ("v0_decay", 0.5f), ("v0_tone", 0.4f), ("v0_drive", 0.35f),
+ ("v1_tune", 0.38f), ("v1_decay", 0.45f), ("v1_tone", 0.5f), ("v1_drive", 0.3f),
+ ("v4_decay", 0.12f), ("v4_tone", 0.35f), ("swing", 0.28f), ("humanize", 0.25f), ("glue", 0.35f));
+ Inst("drums", 12, "Dusty Hip-Hop",
+ ("v0_tune", 0.22f), ("v0_decay", 0.48f), ("v0_tone", 0.25f), ("v0_drive", 0.55f),
+ ("v1_tune", 0.3f), ("v1_tone", 0.3f), ("v1_drive", 0.5f), ("v2_drive", 0.4f),
+ ("v4_tone", 0.25f), ("v4_decay", 0.13f), ("swing", 0.3f), ("humanize", 0.35f), ("glue", 0.4f), ("volume", 0.75f));
+ Inst("drums", 12, "Breakbeat",
+ ("v0_tune", 0.28f), ("v0_decay", 0.45f), ("v0_punch", 0.7f), ("v0_drive", 0.3f),
+ ("v1_tune", 0.5f), ("v1_decay", 0.45f), ("v1_punch", 0.7f), ("v1_drive", 0.3f),
+ ("v5_decay", 0.4f), ("swing", 0.12f), ("humanize", 0.15f), ("glue", 0.45f));
+ Inst("drums", 12, "Drum & Bass",
+ ("v0_tune", 0.35f), ("v0_decay", 0.35f), ("v0_punch", 0.8f), ("v0_drive", 0.2f),
+ ("v1_tune", 0.62f), ("v1_decay", 0.35f), ("v1_tone", 0.55f), ("v1_punch", 0.7f),
+ ("v4_decay", 0.1f), ("v5_decay", 0.35f), ("swing", 0.05f), ("glue", 0.4f));
+ Inst("drums", 12, "UK Garage",
+ ("v0_tune", 0.27f), ("v0_decay", 0.4f), ("v1_tune", 0.55f), ("v1_decay", 0.3f), ("v2_decay", 0.38f),
+ ("v3_tune", 0.55f), ("v4_decay", 0.1f), ("v5_decay", 0.35f), ("swing", 0.35f), ("humanize", 0.1f), ("glue", 0.25f));
+ Inst("drums", 12, "Jersey Club",
+ ("v0_tune", 0.3f), ("v0_decay", 0.4f), ("v0_punch", 0.75f), ("v1_tune", 0.6f), ("v1_decay", 0.3f),
+ ("v2_tune", 0.6f), ("v2_decay", 0.35f), ("v4_decay", 0.08f), ("swing", 0.1f), ("accent", 0.8f), ("glue", 0.3f));
+ Inst("drums", 12, "Footwork",
+ ("v0_tune", 0.12f), ("v0_decay", 0.8f), ("v0_drive", 0.25f), ("v4_decay", 0.08f),
+ ("v7_tune", 0.8f), ("v7_decay", 0.25f), ("v6_tune", 0.6f), ("v6_decay", 0.35f), ("glue", 0.2f));
+ // World · acoustic-ish
+ Inst("drums", 12, "Afro House",
+ ("v0_tune", 0.26f), ("v0_decay", 0.45f), ("v6_tune", 0.4f), ("v6_decay", 0.45f), ("v6_pan", 0.4f),
+ ("v7_tune", 0.45f), ("v7_decay", 0.5f), ("v7_tone", 0.35f), ("v7_pan", 0.62f), ("v3_tune", 0.5f),
+ ("swing", 0.15f), ("humanize", 0.2f), ("glue", 0.2f));
+ Inst("drums", 12, "Latin Percussion",
+ ("v3_tune", 0.62f), ("v3_decay", 0.35f), ("v3_pan", 0.6f), ("v6_tune", 0.55f), ("v6_decay", 0.4f),
+ ("v6_pan", 0.38f), ("v7_tune", 0.6f), ("v7_tone", 0.7f), ("v7_decay", 0.3f), ("v7_pan", 0.66f),
+ ("v0_decay", 0.4f), ("swing", 0.12f), ("humanize", 0.25f));
+ Inst("drums", 12, "Soft Brushes",
+ ("v0_tune", 0.3f), ("v0_decay", 0.4f), ("v0_punch", 0.2f), ("v0_level", 0.6f),
+ ("v1_tone", 0.85f), ("v1_decay", 0.6f), ("v1_punch", 0.2f), ("v1_drive", 0f), ("v1_level", 0.6f),
+ ("v4_tone", 0.85f), ("v4_decay", 0.12f), ("v4_level", 0.55f), ("v5_tone", 0.85f), ("v5_level", 0.5f),
+ ("swing", 0.45f), ("humanize", 0.4f), ("accent", 0.4f), ("glue", 0.1f));
+ // Texture
+ Inst("drums", 12, "Glitch",
+ ("v0_tune", 0.85f), ("v0_decay", 0.1f), ("v0_punch", 1f), ("v1_decay", 0.08f), ("v1_tone", 0.9f),
+ ("v2_tune", 1f), ("v2_decay", 0.1f), ("v7_tone", 1f), ("v7_decay", 0.12f), ("v7_drive", 0.6f),
+ ("v4_decay", 0.02f), ("humanize", 0.5f), ("glue", 0.3f));
+ Inst("drums", 12, "Ambient Pulse",
+ ("v0_tune", 0.2f), ("v0_decay", 0.7f), ("v0_tone", 0.3f), ("v0_punch", 0.2f), ("v0_level", 0.65f),
+ ("v3_level", 0.5f), ("v3_decay", 0.8f), ("v5_decay", 0.9f), ("v5_level", 0.45f), ("v5_tone", 0.3f),
+ ("v7_tune", 0.3f), ("v7_decay", 0.8f), ("v7_level", 0.45f), ("humanize", 0.2f), ("volume", 0.72f));
+ Inst("drums", 12, "Metal Perc",
+ ("v4_tune", 0.8f), ("v4_tone", 0.1f), ("v5_tune", 0.75f), ("v5_tone", 0.15f), ("v5_decay", 0.6f),
+ ("v7_tune", 0.55f), ("v7_tone", 0.9f), ("v7_decay", 0.55f), ("v3_tune", 0.85f), ("v3_drive", 0.4f), ("glue", 0.2f));
// ---- Nota Monolith (kind 13) — mono Model-D synth. Ranges LO..2' = 0/.2/.4/.6/.8/1;
// waves tri/shark/saw/square/wide/narrow = 0/.2/.4/.6/.8/1; tunes bipolar (0.5 = 0).
diff --git a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs b/src/managed/Nota.Infrastructure/Persistence/PresetService.cs
index d5dddf73..bd4b0461 100644
--- a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/PresetService.cs
@@ -34,13 +34,14 @@ public static class PresetService
return string.IsNullOrEmpty(doc.PluginId) ? null : doc;
}
// Built-in instrument: capture the normalized plugin-params by id. Skip kinds whose
- // state isn't fully recallable from params alone — Grain (10) needs the sample,
- // Rhythm (12) its patterns/samples, and the Instrument/Drum racks (3/4) their chains.
- // The Sampler (1) saves its sound — envelope, filter, pitch, loop, voices — and
- // applying it keeps whatever sample is loaded (like its factory presets). Everything
- // else (Synth, Physical, Aurora, Volt, Bass, Pendulum, Operator, Flux, …) is a
- // param-only synth and saves cleanly.
- if (ik is 3 or 4 or 10 or 12) return null;
+ // state isn't fully recallable from params alone — Grain (10) needs the sample and
+ // the Instrument/Drum racks (3/4) their chains. The Sampler (1) saves its sound —
+ // envelope, filter, pitch, loop, voices — and applying it keeps whatever sample is
+ // loaded (like its factory presets). Rhythm (12) saves its kit — every voice's
+ // sound, the groove and the bus — and applying it keeps the steps, the loaded
+ // samples and their regions. Everything else (Synth, Physical, Aurora, Volt, Bass,
+ // Pendulum, Operator, Flux, …) is a param-only synth and saves cleanly.
+ if (ik is 3 or 4 or 10) return null;
{
int pc = engine.PluginParamCount(trackId, -1);
if (pc <= 0) return null;
@@ -234,13 +235,16 @@ public static class PresetService
{
int pc = engine.PluginParamCount(trackId, -1);
// The Sampler's trim and loop points belong to the loaded sample, not the
- // sound: a preset that doesn't name them leaves them where they are.
- bool sampler = engine.TrackInstrumentKind(trackId) == 1;
+ // sound: a preset that doesn't name them leaves them where they are. Likewise
+ // a Rhythm voice's sample region (v{n}_start / _length / _reverse).
+ int kind = engine.TrackInstrumentKind(trackId);
+ bool sampler = kind == 1, rhythm = kind == 12;
for (int i = 0; i < pc; i++)
{
string id = engine.PluginParamId(trackId, -1, i);
bool named = doc.NamedParams is { Count: > 0 } && doc.NamedParams.ContainsKey(id);
if (!named && sampler && id is "start" or "end" or "loopstart" or "loopend") continue;
+ if (!named && rhythm && (id.EndsWith("_start") || id.EndsWith("_length") || id.EndsWith("_reverse"))) continue;
float v = named ? doc.NamedParams![id] : engine.InstrumentParamDefault(trackId, i);
engine.PluginParamSet(trackId, -1, i, v);
}
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
index a368ac38..a7e02d4c 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
@@ -191,6 +191,8 @@ public sealed class VoiceSampleDto
{
public int Voice { get; set; }
public string Sample { get; set; } = "";
+ /// <summary>The voice plays its synth engine; the sample is kept for switching back.</summary>
+ public bool Synth { get; set; }
}
public sealed class SamplerDto
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
index 4a4baa41..92596503 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
@@ -136,10 +136,10 @@ public sealed class ProjectService
var vs = new System.Collections.Generic.List<VoiceSampleDto>();
for (int v = 0; v < 8; v++)
{
- if (engine.RhythmVoiceSource(ti.Id, v) != 1) continue;
+ // A voice keeps its one-shot while it plays the synth, so save it either way.
if (!engine.TryGetRhythmVoiceInfo(ti.Id, v, out var vi) || vi.SampleId == 0) continue;
string? rel = RegisterSample(doc, engine, vi.SampleId, warnings);
- if (rel != null) vs.Add(new VoiceSampleDto { Voice = v, Sample = rel });
+ if (rel != null) vs.Add(new VoiceSampleDto { Voice = v, Sample = rel, Synth = engine.RhythmVoiceSource(ti.Id, v) != 1 });
}
if (vs.Count > 0) instDto.VoiceSamples = vs;
}
@@ -556,8 +556,13 @@ public sealed class ProjectService
// Nota Rhythm Phase 2: reload each voice's one-shot from the bundle.
if (id > 0 && t.Instrument is { Kind: 12, VoiceSamples: { } vsl })
foreach (var vs in vsl)
- if (vs.Sample is { Length: > 0 } && !engine.SetRhythmVoiceSample(id, vs.Voice, ResolveInBundle(bundleDir, vs.Sample)))
+ {
+ if (vs.Sample is not { Length: > 0 }) continue;
+ if (!engine.SetRhythmVoiceSample(id, vs.Voice, ResolveInBundle(bundleDir, vs.Sample)))
warnings.Add($"Couldn't reload Rhythm voice sample \"{vs.Sample}\".");
+ else if (vs.Synth)
+ engine.InstrumentAction(id, RhythmModel.A_SetSource, vs.Voice, 0f); // loading switches to Sample
+ }
}
}
else if (t.Type == 3)
diff --git a/src/managed/Nota.Mcp/Tools/RhythmTools.cs b/src/managed/Nota.Mcp/Tools/RhythmTools.cs
index c3a9aaed..ee771810 100644
--- a/src/managed/Nota.Mcp/Tools/RhythmTools.cs
+++ b/src/managed/Nota.Mcp/Tools/RhythmTools.cs
@@ -4,13 +4,17 @@
// MCP tools — Nota Rhythm (drum machine, instrument kind 12). Eight fixed voices (Kick, Snare,
// Clap, Rim, Closed Hat, Open Hat, Tom, Perc), each with an internal 16-step sequencer across four
// pattern banks (A–D). Step edits apply to the CURRENTLY-selected bank (select_rhythm_bank first).
-// Per-voice knobs (Tune/Decay/Punch/Tone/Drive/Level/Pan) + Swing/Humanize/Accent are plugin
-// parameters — read/write them with get_instrument_params / set_instrument_param. A voice can play
-// its built-in synth engine or a loaded one-shot sample.
+// A step has a velocity (below 0.45 = a quiet step) and an accent flag. Per-voice sound (Tune /
+// Decay / Punch / Tone / Drive / Level / Pan, and for a sample voice Start / Length / Reverse)
+// and the groove (Swing / Humanize / Accent / Glue / Volume) are plugin parameters — set them with
+// set_rhythm_voice / set_rhythm_perform, or get_instrument_params / set_instrument_param_by_id.
+// A voice plays its built-in synth engine or a loaded one-shot sample.
using System.ComponentModel;
+using System.Text;
using ModelContextProtocol.Server;
using Nota.Application;
+using RM = Nota.Application.RhythmModel;
namespace Nota.Mcp.Tools;
@@ -18,61 +22,102 @@ namespace Nota.Mcp.Tools;
public sealed class RhythmTools(IAudioEngine engine, IEngineDispatch dispatch, IArrangementRefresh refresh)
: EngineTools(engine, dispatch, refresh)
{
- // action ids — must match RhythmMachine::Act.
- private const int A_ToggleStep = 0, A_SetVel = 1, A_ToggleAccent = 2, A_SelectBank = 3, A_ClearBank = 4, A_SetSource = 6;
- private const int Voices = 8, Steps = 16, Banks = 4;
- private static readonly string[] VoiceNames = { "Kick", "Snare", "Clap", "Rim", "Closed Hat", "Open Hat", "Tom", "Perc" };
+ private const int Voices = RM.Voices, Steps = RM.Steps, Banks = RM.Banks;
public sealed record Step(int Index, float Velocity, bool Accent);
- public sealed record VoiceInfo(int Index, string Name, string Source, bool HasSample, Step[] Steps);
- public sealed record RhythmSnapshot(int CurrentBank, int SelectedVoice, int Bank, VoiceInfo[] Voices);
+ public sealed record VoiceSound(float Tune, float Decay, float Punch, float Tone, float Drive, float Level, float Pan,
+ float Start, float Length, bool Reverse, string TuneText, string DecayText);
+ public sealed record VoiceInfo(int Index, string Name, string Source, bool HasSample, Step[] Steps,
+ string Engine = "", int MidiNote = 0, string SampleName = "", string Pattern = "", VoiceSound? Sound = null);
+ public sealed record RhythmSnapshot(int CurrentBank, int SelectedVoice, int Bank, VoiceInfo[] Voices,
+ string Summary = "", string Guide = "", float Swing = 0, float Humanize = 0, float Accent = 0, float Glue = 0, float Volume = 0,
+ int PlayingStep = -1, int SoundingVoices = 0);
- // Reads the instrument state blob and exposes a per-step accessor (mirrors RhythmInstrumentCard).
- private readonly record struct Pattern(byte[] St, int PatBase, int CurrentBank, int SelectedVoice)
+ private RM.Pattern ReadPattern(int trackId) => RM.Parse(E.GetPluginState(trackId, -1), E.PluginParamCount(trackId, -1));
+
+ private Func<string, float> Getter(int trackId)
{
- private int Ix(int bank, int v, int s) => PatBase + ((bank * Voices + v) * Steps + s) * 3;
- public bool On(int bank, int v, int s) { int i = Ix(bank, v, s); return i < St.Length && St[i] != 0; }
- public float Vel(int bank, int v, int s) { int i = Ix(bank, v, s) + 1; return i < St.Length ? St[i] / 255f : 0.7f; }
- public bool Accent(int bank, int v, int s) { int i = Ix(bank, v, s) + 2; return i < St.Length && St[i] != 0; }
+ int pc = E.PluginParamCount(trackId, -1);
+ var vals = new Dictionary<string, float>();
+ for (int i = 0; i < pc; i++) vals[E.PluginParamId(trackId, -1, i)] = E.PluginParamGet(trackId, -1, i);
+ return id => vals.TryGetValue(id, out var v) ? v : 0f;
}
- private Pattern ReadPattern(int trackId)
+ private Dictionary<string, int> Ids(int trackId)
{
- byte[] st = E.GetPluginState(trackId, -1);
int pc = E.PluginParamCount(trackId, -1);
- int bankByte = 4 + pc * 4, patBase = bankByte + 4;
- int bank = st.Length > bankByte ? Math.Clamp(st[bankByte], (byte)0, (byte)(Banks - 1)) : 0;
- int sel = st.Length > bankByte + 1 ? Math.Clamp(st[bankByte + 1], (byte)0, (byte)(Voices - 1)) : 0;
- return new Pattern(st, patBase, bank, sel);
+ var ids = new Dictionary<string, int>();
+ for (int i = 0; i < pc; i++) ids[E.PluginParamId(trackId, -1, i)] = i;
+ return ids;
+ }
+
+ /// <summary>A row as text: x on, X accent, o quiet, . off.</summary>
+ private static string RowText(RM.Pattern p, int b, int v)
+ {
+ var sb = new StringBuilder(Steps);
+ for (int s = 0; s < Steps; s++)
+ sb.Append(!p.On[b, v, s] ? '.' : p.Acc[b, v, s] ? 'X' : p.Quiet(b, v, s) ? 'o' : 'x');
+ return sb.ToString();
}
[McpServerTool(Name = "get_rhythm"), Description(
- "Snapshot of a Nota Rhythm track: current bank + selected voice, and for a bank (default = current) "
- + "each voice's name, source (synth|sample) and its ON steps (index, velocity 0..1, accent).")]
+ "Snapshot of a Nota Rhythm track: current bank + selected voice; for a bank (default = current) each voice's name, "
+ + "engine, MIDI note, source (synth|sample), loaded sample name, its ON steps (index, velocity 0..1, accent), the row "
+ + "as text (x on · X accent · o quiet · . off, 16 chars) and its sound (normalized params + tune/decay in units); "
+ + "the groove (swing, humanize, accent, glue, volume, all 0..1), the step playing now (-1 stopped), a one-line "
+ + "summary of the selected voice and a guide to every parameter.")]
public Task<RhythmSnapshot> GetRhythm(int trackId, [Description("Bank 0..3 (A–D), or -1 for the current bank")] int bank = -1) => Read(() =>
{
var p = ReadPattern(trackId);
+ var g = Getter(trackId);
int b = bank >= 0 && bank < Banks ? bank : p.CurrentBank;
var voices = new VoiceInfo[Voices];
for (int v = 0; v < Voices; v++)
{
var steps = new List<Step>();
- for (int s = 0; s < Steps; s++) if (p.On(b, v, s)) steps.Add(new Step(s, p.Vel(b, v, s), p.Accent(b, v, s)));
- string src = E.RhythmVoiceSource(trackId, v) == 1 ? "sample" : "synth";
- bool hasSample = E.TryGetRhythmVoiceInfo(trackId, v, out var vi) && vi.SampleId != 0;
- voices[v] = new VoiceInfo(v, VoiceNames[v], src, hasSample, steps.ToArray());
+ for (int s = 0; s < Steps; s++) if (p.On[b, v, s]) steps.Add(new Step(s, (float)Math.Round(p.Vel[b, v, s], 3), p.Acc[b, v, s]));
+ bool smp = E.RhythmVoiceSource(trackId, v) == 1;
+ long sid = E.TryGetRhythmVoiceInfo(trackId, v, out var vi) ? vi.SampleId : 0;
+ float F(string id) => g(RM.Id(v, id));
+ string tune = smp ? RM.Semis(RM.SampleSemis(F("tune"))) : $"{RM.TuneHz(v, F("tune")):0} Hz";
+ string decay = RM.Ms(smp ? RM.SampleDecaySeconds(F("decay")) : RM.DecaySeconds(v, F("decay"), F("punch")));
+ var sound = new VoiceSound(F("tune"), F("decay"), F("punch"), F("tone"), F("drive"), F("level"), F("pan"),
+ F("start"), F("length"), F("reverse") >= 0.5f, tune, decay);
+ voices[v] = new VoiceInfo(v, RM.VoiceNames[v], smp ? "sample" : "synth", sid != 0, steps.ToArray(),
+ RM.Engines[v], RM.MidiNotes[v], sid != 0 ? E.SampleName(sid) : "", RowText(p, b, v), sound);
}
- return new RhythmSnapshot(p.CurrentBank, p.SelectedVoice, b, voices);
+ var sc = new float[RM.ScopeLength];
+ int n = E.InstrumentScope(trackId, sc);
+ int sel = p.SelectedVoice;
+ bool selSample = E.RhythmVoiceSource(trackId, sel) == 1 && voices[sel].HasSample;
+ return new RhythmSnapshot(p.CurrentBank, sel, b, voices,
+ RM.Summary(g, p, sel, selSample, voices[sel].SampleName), RM.Guide,
+ g("swing"), g("humanize"), g("accent"), g("glue"), g("volume"),
+ n > RM.S_Step ? (int)Math.Round(sc[RM.S_Step]) : -1, Math.Max(0, E.InstrumentVoiceCount(trackId)));
});
[McpServerTool(Name = "select_rhythm_bank"), Description("Select the active Rhythm pattern bank (0..3 = A–D). Step edits and playback use this bank.")]
- public Task SelectRhythmBank(int trackId, int bank) => Mutate(() => E.InstrumentAction(trackId, A_SelectBank, Math.Clamp(bank, 0, Banks - 1), 0f));
+ public Task SelectRhythmBank(int trackId, int bank) => Mutate(() => E.InstrumentAction(trackId, RM.A_SelectBank, Math.Clamp(bank, 0, Banks - 1), 0f));
+
+ [McpServerTool(Name = "select_rhythm_voice"), Description("Select the voice (0..7) the Rhythm editor shows and edits.")]
+ public Task SelectRhythmVoice(int trackId, int voice) => Mutate(() => E.InstrumentAction(trackId, RM.A_SelectVoice, Math.Clamp(voice, 0, Voices - 1), 0f));
[McpServerTool(Name = "clear_rhythm_bank"), Description("Clear all steps + accents in a Rhythm bank (0..3). Velocities are left as-is.")]
- public Task ClearRhythmBank(int trackId, int bank) => Mutate(() => E.InstrumentAction(trackId, A_ClearBank, Math.Clamp(bank, 0, Banks - 1), 0f));
+ public Task ClearRhythmBank(int trackId, int bank) => Mutate(() => E.InstrumentAction(trackId, RM.A_ClearBank, Math.Clamp(bank, 0, Banks - 1), 0f));
+
+ [McpServerTool(Name = "copy_rhythm_bank"), Description("Copy a whole Rhythm bank (every voice's steps, velocities and accents) onto another: from / to 0..3 (A–D).")]
+ public Task<string> CopyRhythmBank(int trackId, int from, int to) => Mutate(() =>
+ {
+ if (from < 0 || from >= Banks || to < 0 || to >= Banks || from == to) return "error: from and to must be different banks 0..3";
+ E.InstrumentAction(trackId, RM.A_CopyBank, from * Banks + to, 0f);
+ return $"copied bank {RM.BankNames[from]} to {RM.BankNames[to]}";
+ });
+
+ [McpServerTool(Name = "clear_rhythm_voice"), Description("Clear one voice's steps (0..7) in the current bank.")]
+ public Task ClearRhythmVoice(int trackId, int voice) => Mutate(() => E.InstrumentAction(trackId, RM.A_ClearVoice, Math.Clamp(voice, 0, Voices - 1), 0f));
[McpServerTool(Name = "set_rhythm_step"), Description(
- "Set one step of a voice in the current bank (idempotent): on/off, velocity 0..1, accent. "
+ "Set one step of a voice in the current bank (idempotent): on/off, velocity 0..1 (below 0.45 = quiet), accent. "
+ "voice 0..7 (0 Kick .. 7 Perc), step 0..15.")]
public Task SetRhythmStep(int trackId, int voice, int step, bool on, float velocity = 0.7f, bool accent = false) => Mutate(() =>
{
@@ -94,28 +139,138 @@ public sealed class RhythmTools(IAudioEngine engine, IEngineDispatch dispatch, I
}
});
+ [McpServerTool(Name = "set_rhythm_pattern"), Description(
+ "Program voices from text rows in the current bank — the quickest way to write a beat. rows maps a voice (index "
+ + "0..7 or name: kick, snare, clap, rim, ch/closed hat, oh/open hat, tom, perc) to 16 characters, one per 1/16 step: "
+ + "x = on (velocity 0.7), X = accent, o = quiet (0.3), . or - = off; spaces and | are ignored (\"x...|x...|x...|x...\"). "
+ + "Voices not named keep their steps. Returns each programmed row, or an error naming what it could not read.")]
+ public Task<string> SetRhythmPattern(int trackId, Dictionary<string, string> rows) => Mutate(() =>
+ {
+ var errors = new List<string>();
+ var done = new List<string>();
+ var p = ReadPattern(trackId);
+ foreach (var (key, row) in rows)
+ {
+ int v = VoiceIndex(key);
+ if (v < 0) { errors.Add($"voice '{key}'"); continue; }
+ var cells = row.Where(c => c is not ' ' and not '|').ToArray();
+ if (cells.Length != Steps || cells.Any(c => "xXo.-".IndexOf(c) < 0)) { errors.Add($"row '{row}' (16 of x X o . -)"); continue; }
+ for (int s = 0; s < Steps; s++)
+ {
+ char c = cells[s];
+ if (c is '.' or '-') SetStep(trackId, p, v, s, false, 0f, false);
+ else SetStep(trackId, p, v, s, true, c == 'o' ? RM.QuietVel : c == 'X' ? 0.9f : RM.NormalVel, c == 'X');
+ }
+ done.Add($"{RM.VoiceNames[v]} {new string(cells)}");
+ }
+ string res = string.Join(" · ", done);
+ return errors.Count == 0 ? res : $"error: could not use {string.Join(", ", errors)}" + (res.Length > 0 ? " · " + res : "");
+ });
+
+ [McpServerTool(Name = "set_rhythm_voice"), Description(
+ "Shape one Rhythm voice (0..7 or its name); every argument is optional and only the given ones change. All 0..1 "
+ + "(see get_rhythm's guide): tune, decay, punch, tone, drive, level, pan (.5 centre); for a sample voice semitones "
+ + "(-12..12, overrides tune), start and length (the region, fractions of the file) and reverse. Returns the voice's "
+ + "summary line.")]
+ public Task<string> SetRhythmVoice(int trackId, string voice, float? tune = null, float? decay = null, float? punch = null,
+ float? tone = null, float? drive = null, float? level = null, float? pan = null, double? semitones = null,
+ float? start = null, float? length = null, bool? reverse = null) => Mutate(() =>
+ {
+ if (E.TrackInstrumentKind(trackId) != RM.Kind) return $"error: track {trackId} is not a Nota Rhythm";
+ int v = VoiceIndex(voice);
+ if (v < 0) return $"error: voice '{voice}' (0..7 or kick, snare, clap, rim, ch, oh, tom, perc)";
+ var ids = Ids(trackId);
+ void Set(string p, float? val) { if (val is { } x && ids.TryGetValue(RM.Id(v, p), out var i)) E.PluginParamSet(trackId, -1, i, Math.Clamp(x, 0f, 1f)); }
+ Set("tune", tune); Set("decay", decay); Set("punch", punch); Set("tone", tone); Set("drive", drive);
+ Set("level", level); Set("pan", pan); Set("start", start); Set("length", length);
+ if (semitones is { } st) Set("tune", RM.SampleSemisNorm(st));
+ if (reverse is { } r) Set("reverse", r ? 1f : 0f);
+ return VoiceLine(trackId, v);
+ });
+
+ [McpServerTool(Name = "set_rhythm_perform"), Description(
+ "Set the Rhythm groove and bus; every argument optional, all 0..1: swing (delays every second 16th, 1 = half a step), "
+ + "humanize (velocity jitter), accent (how much louder accented steps play), glue (bus compressor, 0 = off), "
+ + "volume (master). Returns the new values.")]
+ public Task<string> SetRhythmPerform(int trackId, float? swing = null, float? humanize = null, float? accent = null,
+ float? glue = null, float? volume = null) => Mutate(() =>
+ {
+ if (E.TrackInstrumentKind(trackId) != RM.Kind) return $"error: track {trackId} is not a Nota Rhythm";
+ var ids = Ids(trackId);
+ void Set(string id, float? val) { if (val is { } x && ids.TryGetValue(id, out var i)) E.PluginParamSet(trackId, -1, i, Math.Clamp(x, 0f, 1f)); }
+ Set("swing", swing); Set("humanize", humanize); Set("accent", accent); Set("glue", glue); Set("volume", volume);
+ var g = Getter(trackId);
+ return $"swing {RM.Pct(g("swing"))} · humanize {RM.Pct(g("humanize"))} · accent {RM.Pct(g("accent"))} · glue {RM.Pct(g("glue"))} · volume {RM.Pct(g("volume"))}";
+ });
+
+ [McpServerTool(Name = "audition_rhythm_voice"), Description("Play one Rhythm voice (0..7 or its name) once now, at velocity 0..1 — to hear a sound while shaping it.")]
+ public Task<string> AuditionRhythmVoice(int trackId, string voice, float velocity = 0.8f) => Mutate(() =>
+ {
+ int v = VoiceIndex(voice);
+ if (v < 0) return $"error: voice '{voice}'";
+ E.InstrumentAction(trackId, RM.A_Audition, v, Math.Clamp(velocity, 0f, 1f));
+ return $"played {RM.VoiceNames[v]}";
+ });
+
[McpServerTool(Name = "set_rhythm_voice_source"), Description("Switch a Rhythm voice between its built-in synth engine and a loaded sample. source = synth | sample (sample requires a loaded one-shot).")]
public Task SetRhythmVoiceSource(int trackId, int voice, [Description("synth | sample")] string source)
- => Mutate(() => E.InstrumentAction(trackId, A_SetSource, Math.Clamp(voice, 0, Voices - 1), source.Equals("sample", StringComparison.OrdinalIgnoreCase) ? 1f : 0f));
+ => Mutate(() => E.InstrumentAction(trackId, RM.A_SetSource, Math.Clamp(voice, 0, Voices - 1), source.Equals("sample", StringComparison.OrdinalIgnoreCase) ? 1f : 0f));
+
+ [McpServerTool(Name = "load_rhythm_voice_sample"), Description(
+ "Load a one-shot audio file into a Rhythm voice (0..7) and switch that voice to Sample mode; the voice's tune goes to "
+ + "the sample's own pitch (0 st) and its region to the whole file.")]
+ public Task<bool> LoadRhythmVoiceSample(int trackId, int voice, string path) => Mutate(() =>
+ {
+ int v = Math.Clamp(voice, 0, Voices - 1);
+ if (!E.SetRhythmVoiceSample(trackId, v, path)) return false;
+ var ids = Ids(trackId);
+ foreach (var (p, val) in new[] { ("tune", 0.5f), ("start", 0f), ("length", 1f) })
+ if (ids.TryGetValue(RM.Id(v, p), out var i)) E.PluginParamSet(trackId, -1, i, val);
+ return true;
+ });
- [McpServerTool(Name = "load_rhythm_voice_sample"), Description("Load a one-shot audio file into a Rhythm voice (0..7) and switch that voice to Sample mode.")]
- public Task<bool> LoadRhythmVoiceSample(int trackId, int voice, string path) => Mutate(() => E.SetRhythmVoiceSample(trackId, Math.Clamp(voice, 0, Voices - 1), path));
+ private string VoiceLine(int trackId, int v)
+ {
+ var p = ReadPattern(trackId);
+ bool smp = E.RhythmVoiceSource(trackId, v) == 1 && E.TryGetRhythmVoiceInfo(trackId, v, out var vi) && vi.SampleId != 0;
+ string name = smp && E.TryGetRhythmVoiceInfo(trackId, v, out var vi2) ? E.SampleName(vi2.SampleId) : "";
+ return RM.Summary(Getter(trackId), p, v, smp, name);
+ }
+
+ private static int VoiceIndex(string key)
+ {
+ var k = key.Trim().ToLowerInvariant();
+ if (int.TryParse(k, out int n)) return n is >= 0 and < Voices ? n : -1;
+ return k switch
+ {
+ "kick" or "bd" => 0,
+ "snare" or "sd" => 1,
+ "clap" or "cp" => 2,
+ "rim" or "rimshot" or "rs" => 3,
+ "ch" or "closed hat" or "closedhat" or "closed" or "hh" => 4,
+ "oh" or "open hat" or "openhat" or "open" => 5,
+ "tom" => 6,
+ "perc" or "percussion" => 7,
+ _ => -1,
+ };
+ }
- // Idempotent single-step write against a freshly-read pattern (current bank).
- private void SetStep(int trackId, in Pattern p, int voice, int step, bool on, float velocity, bool accent)
+ // Idempotent single-step write against a freshly-read pattern (current bank); keeps it in sync.
+ private void SetStep(int trackId, RM.Pattern p, int voice, int step, bool on, float velocity, bool accent)
{
int v = Math.Clamp(voice, 0, Voices - 1), s = Math.Clamp(step, 0, Steps - 1), b = p.CurrentBank;
int arg = v * Steps + s;
- bool curOn = p.On(b, v, s);
if (on)
{
- if (!curOn) E.InstrumentAction(trackId, A_ToggleStep, arg, 0f); // turn on
- E.InstrumentAction(trackId, A_SetVel, arg, Math.Clamp(velocity, 0f, 1f)); // set velocity
- if (p.Accent(b, v, s) != accent) E.InstrumentAction(trackId, A_ToggleAccent, arg, 0f);
+ if (!p.On[b, v, s]) { E.InstrumentAction(trackId, RM.A_ToggleStep, arg, 0f); p.On[b, v, s] = true; }
+ E.InstrumentAction(trackId, RM.A_SetVel, arg, Math.Clamp(velocity, 0f, 1f));
+ p.Vel[b, v, s] = velocity;
+ if (p.Acc[b, v, s] != accent) { E.InstrumentAction(trackId, RM.A_ToggleAccent, arg, 0f); p.Acc[b, v, s] = accent; }
}
- else if (curOn)
+ else
{
- E.InstrumentAction(trackId, A_ToggleStep, arg, 0f); // turn off
+ if (p.On[b, v, s]) { E.InstrumentAction(trackId, RM.A_ToggleStep, arg, 0f); p.On[b, v, s] = false; }
+ if (p.Acc[b, v, s]) { E.InstrumentAction(trackId, RM.A_ToggleAccent, arg, 0f); p.Acc[b, v, s] = false; }
}
}
}
diff --git a/src/native/nota.engine/src/RhythmMachine.h b/src/native/nota.engine/src/RhythmMachine.h
index c315b2fb..15317d0f 100644
--- a/src/native/nota.engine/src/RhythmMachine.h
+++ b/src/native/nota.engine/src/RhythmMachine.h
@@ -5,19 +5,25 @@
// groovebox: eight drum voices, each a compact synth engine (electronic drum generation —
// analog/FM kick, noise snare, metal hats…), programmed on an internal 16-step sequencer
// that plays synced to the DAW transport. Incoming MIDI notes also trigger the mapped voice
-// live (finger-drumming). Phase 1 is synth-only; per-voice samples are a later phase.
+// live (finger-drumming). Any voice can instead play a loaded one-shot (a Start / Length
+// region of it, forwards or reversed).
//
// Voice engines (retriggered, monophonic): Kick (sine + pitch-drop + click), Snare (tone
// sines + noise snap), Clap (noise bursts + tail), Rim (band-passed noise click), Closed/
// Open Hat (HP noise — closed chokes open, 808-style), Tom (sine + pitch env), Perc (ring).
//
// Sequencer: setTransport() feeds the beat clock; a 1/16 step = 0.25 beat, 16 steps = 1 bar.
-// Swing delays odd 16ths; Humanize jitters timing + velocity. Four pattern banks (A–D).
+// Swing delays odd 16ths; Humanize jitters velocity. Four pattern banks (A–D).
+//
+// Bus: the voices sum through Glue (a gentle compressor) into Volume.
//
// The 7 per-voice knobs (Tune/Decay/Punch/Tone/Drive/Level/Pan) + 4 globals ride the plugin-
-// param interface (normalized 0..1) → automation / persist / clone for free. The step
-// patterns are structural state (getState/setState blob + the action() UI channel), not
-// params. Header-only, allocation-free after construction. Name & DSP are Nota's own.
+// param interface (normalized 0..1) → automation / persist / clone for free. Appended after
+// them (param order is the persisted layout — append only): per-voice sample Start / Length /
+// Reverse, then Glue (a bus compressor on the kit sum). The step patterns are structural
+// state (getState/setState blob + the action() UI channel), not params. A step is on/off with
+// a velocity (a "quiet" step is just a low one) and an accent flag. Header-only, allocation-
+// free after construction. Name & DSP are Nota's own.
#pragma once
@@ -40,15 +46,24 @@ public:
static constexpr int kVoices = 8;
static constexpr int kSteps = 16;
static constexpr int kBanks = 4;
- static constexpr int kPV = 7; // params per voice
- static constexpr int kNumParams = kVoices * kPV + 4; // + Swing, Humanize, Accent, Volume
+ static constexpr int kPV = 7; // params per voice (v1 block)
+ static constexpr int kPX = 3; // appended per-voice params (sample region)
+ static constexpr int kLegacyParams = kVoices * kPV + 4; // RTH1 blobs carry exactly these
+ static constexpr int kExtra = kLegacyParams; // first appended per-voice param
+ static constexpr int kNumParams = kExtra + kVoices * kPX + 1; // + Glue
enum VP { Tune = 0, Decay, Punch, Tone, Drive, Level, Pan };
- enum GP { Swing = kVoices * kPV, Humanize, Accent, Volume };
- enum Scope { S_Step = 0, S_Flash0, kScopeN = S_Flash0 + kVoices };
+ enum XP { Start = 0, Length, Reverse };
+ enum GP { Swing = kVoices * kPV, Humanize, Accent, Volume, Glue = kExtra + kVoices * kPX };
+ // scopeRead layout: the playing step (-1 stopped), the current bank, an edit revision that
+ // bumps on every pattern change (so an editor re-reads the blob after an MCP edit), the
+ // sounding-voice count, the glue gain reduction (dB, ≥ 0), then per voice a trigger flash
+ // (1 on a hit, decaying) and the sample play position (0..1 of the file, -1 idle).
+ enum Scope { S_Step = 0, S_Bank, S_Rev, S_Active, S_Glue, S_Flash0, S_Pos0 = S_Flash0 + kVoices, kScopeN = S_Pos0 + kVoices };
// action() ids (UI editing channel).
- enum Act { A_ToggleStep = 0, A_SetVel, A_ToggleAccent, A_SelectBank, A_ClearBank, A_SelectVoice, A_SetSource };
+ enum Act { A_ToggleStep = 0, A_SetVel, A_ToggleAccent, A_SelectBank, A_ClearBank, A_SelectVoice, A_SetSource,
+ A_CopyBank, A_Audition, A_ClearVoice };
enum Source { Synth = 0, Sample = 1 };
RhythmMachine() {
@@ -56,12 +71,18 @@ public:
for (int v = 0; v < kVoices; ++v) {
setP(v, Tune, 0.35f); setP(v, Decay, 0.5f); setP(v, Punch, 0.5f);
setP(v, Tone, 0.5f); setP(v, Drive, 0.15f); setP(v, Level, 0.8f); setP(v, Pan, 0.5f);
+ setX(v, Start, 0.0f); setX(v, Length, 1.0f); setX(v, Reverse, 0.0f);
}
// Per-voice character tweaks.
setP(0, Tune, 0.22f); setP(0, Decay, 0.55f); // Kick — low, long
setP(4, Decay, 0.14f); // Closed hat — short
setP(5, Decay, 0.5f); // Open hat — long
pn_[Swing].store(0.0f); pn_[Humanize].store(0.0f); pn_[Accent].store(0.7f); pn_[Volume].store(0.8f);
+ pn_[Glue].store(0.0f);
+ for (auto& p : pendingTrig_) p.store(-1.0f, std::memory_order_relaxed);
+ for (auto& sc : scope_) sc.store(0.0f, std::memory_order_relaxed);
+ scope_[S_Step].store(-1.0f, std::memory_order_relaxed);
+ for (int v = 0; v < kVoices; ++v) scope_[S_Pos0 + v].store(-1.0f, std::memory_order_relaxed);
clearAll();
// A minimal four-on-the-floor so a fresh instance makes a sound.
for (int s = 0; s < 16; s += 4) { on_[0][0][s] = 1; vel_[0][0][s] = 200; }
@@ -81,15 +102,21 @@ public:
// ---- parameters -------------------------------------------------------
int32_t pluginParamCount() const override { return kNumParams; }
+ // Names group in the automation menu by their head: "Kick › Tune", "Perform › Swing",
+ // "Master › Glue". Ids never change.
std::string pluginParamId(int32_t i) const override {
if (i < 0 || i >= kNumParams) return {};
+ if (i == Glue) return "glue";
+ if (i >= kExtra) { static const char* x[] = {"start","length","reverse"}; int k = i - kExtra; return "v" + std::to_string(k / kPX) + "_" + x[k % kPX]; }
if (i >= kVoices * kPV) { static const char* g[] = {"swing","humanize","accent","volume"}; return g[i - kVoices * kPV]; }
static const char* pid[] = {"tune","decay","punch","tone","drive","level","pan"};
return "v" + std::to_string(i / kPV) + "_" + pid[i % kPV];
}
std::string pluginParamName(int32_t i) const override {
if (i < 0 || i >= kNumParams) return {};
- if (i >= kVoices * kPV) { static const char* g[] = {"Swing","Humanize","Accent","Volume"}; return g[i - kVoices * kPV]; }
+ if (i == Glue) return "Master Glue";
+ if (i >= kExtra) { static const char* x[] = {"Start","Length","Reverse"}; int k = i - kExtra; return std::string(kVoiceNames[k / kPX]) + " " + x[k % kPX]; }
+ if (i >= kVoices * kPV) { static const char* g[] = {"Perform Swing","Perform Humanize","Perform Accent","Master Volume"}; return g[i - kVoices * kPV]; }
static const char* pn[] = {"Tune","Decay","Punch","Tone","Drive","Level","Pan"};
return std::string(kVoiceNames[i / kPV]) + " " + pn[i % kPV];
}
@@ -102,6 +129,7 @@ public:
// ---- UI editing channel ----------------------------------------------
void action(int32_t id, int32_t iarg, float farg) override {
+ if (id != A_SelectVoice && id != A_Audition) rev_.fetch_add(1, std::memory_order_relaxed);
switch (id) {
case A_ToggleStep: { int v = iarg / kSteps, s = iarg % kSteps; if (valid(v, s)) { uint8_t& o = on_[bank_][v][s]; o = o ? 0 : 1; if (o && vel_[bank_][v][s] == 0) vel_[bank_][v][s] = 180; } break; }
case A_SetVel: { int v = iarg / kSteps, s = iarg % kSteps; if (valid(v, s)) vel_[bank_][v][s] = (uint8_t)std::clamp((int)std::lround(farg * 255.0f), 0, 255); break; }
@@ -110,6 +138,17 @@ public:
case A_ClearBank: { int b = (iarg >= 0 && iarg < kBanks) ? iarg : bank_; for (int v = 0; v < kVoices; ++v) for (int s = 0; s < kSteps; ++s) { on_[b][v][s] = 0; acc_[b][v][s] = 0; } break; }
case A_SelectVoice: if (iarg >= 0 && iarg < kVoices) selVoice_ = (uint8_t)iarg; break;
case A_SetSource: if (iarg >= 0 && iarg < kVoices) src_[iarg] = (farg > 0.5f && smp_[iarg]) ? (uint8_t)Sample : (uint8_t)Synth; break;
+ case A_CopyBank: { // iarg = src * kBanks + dst: the whole bank (steps, velocities, accents)
+ int from = iarg / kBanks, to = iarg % kBanks;
+ if (from >= 0 && from < kBanks && to >= 0 && to < kBanks && from != to) {
+ std::memcpy(on_[to], on_[from], sizeof(on_[0])); std::memcpy(vel_[to], vel_[from], sizeof(vel_[0])); std::memcpy(acc_[to], acc_[from], sizeof(acc_[0]));
+ }
+ break;
+ }
+ case A_Audition: // play a voice now (the kit list, a pad click); consumed by render()
+ if (iarg >= 0 && iarg < kVoices) pendingTrig_[iarg].store(std::clamp(farg, 0.0f, 1.0f), std::memory_order_relaxed);
+ break;
+ case A_ClearVoice: if (iarg >= 0 && iarg < kVoices) for (int s = 0; s < kSteps; ++s) { on_[bank_][iarg][s] = 0; acc_[bank_][iarg][s] = 0; } break;
default: break;
}
}
@@ -120,12 +159,14 @@ public:
smp_[v] = std::move(b);
src_[v] = smp_[v] ? (uint8_t)Sample : (uint8_t)Synth;
}
+ int32_t activeVoiceCount() const override { return active_.load(std::memory_order_relaxed); }
int32_t voiceSource(int v) const { return (v >= 0 && v < kVoices) ? src_[v] : 0; }
int64_t voiceSampleId(int v) const { return (v >= 0 && v < kVoices && smp_[v]) ? smp_[v]->id : 0; }
std::shared_ptr<SampleBuffer> voiceSampleBuf(int v) const { return (v >= 0 && v < kVoices) ? smp_[v] : nullptr; }
// ---- project state ----------------------------------------------------
- // Layout: [u32 magic]['kNumParams' floats]['bank','sel',2 reserved]['on,vel,acc' per bank/voice/step].
+ // Layout: [u32 magic]['kNumParams' floats]['bank','sel',2 reserved]['on,vel,acc' per bank/voice/step]
+ // ['src' per voice]. RTH1 (before the sample region + Glue) carries kLegacyParams floats.
std::vector<uint8_t> getState() const override {
std::vector<uint8_t> b;
b.reserve(8 + kNumParams * 4 + kBanks * kVoices * kSteps * 3);
@@ -142,8 +183,12 @@ public:
int off = 0;
uint32_t magic = 0; for (int i = 0; i < 4; ++i) magic |= (uint32_t)data[i] << (i * 8);
off = 4;
- if (magic != kMagic) return; // unknown — keep defaults
- for (int i = 0; i < kNumParams && off + 4 <= size; ++i, off += 4) { float v; std::memcpy(&v, data + off, 4); if (std::isfinite(v)) pn_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed); }
+ int nParams;
+ if (magic == kMagic) nParams = kNumParams;
+ else if (magic == kMagicV1) nParams = kLegacyParams;
+ else return; // unknown — keep defaults
+ rev_.fetch_add(1, std::memory_order_relaxed);
+ for (int i = 0; i < nParams && off + 4 <= size; ++i, off += 4) { float v; std::memcpy(&v, data + off, 4); if (std::isfinite(v)) pn_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed); }
if (off + 2 <= size) { bank_ = (uint8_t)std::min<int>(data[off], kBanks - 1); selVoice_ = (uint8_t)std::min<int>(data[off + 1], kVoices - 1); off += 4; }
for (int bk = 0; bk < kBanks; ++bk) for (int v = 0; v < kVoices; ++v) for (int s = 0; s < kSteps; ++s) {
if (off + 3 > size) return;
@@ -156,6 +201,7 @@ public:
for (int i = 0; i < kNumParams; ++i) r->pn_[i].store(pn_[i].load(std::memory_order_relaxed), std::memory_order_relaxed);
std::memcpy(r->on_, on_, sizeof(on_)); std::memcpy(r->vel_, vel_, sizeof(vel_)); std::memcpy(r->acc_, acc_, sizeof(acc_));
r->bank_ = bank_; r->selVoice_ = selVoice_;
+ r->rev_.store(rev_.load(std::memory_order_relaxed) + 1, std::memory_order_relaxed);
for (int v = 0; v < kVoices; ++v) { r->smp_[v] = smp_[v]; r->src_[v] = src_[v]; } // share sample buffers (immutable)
r->setSampleRate(sampleRate_);
return r;
@@ -164,6 +210,8 @@ public:
int32_t scopeRead(float* out, int32_t maxN) const override {
const int n = std::min(maxN, (int)kScopeN);
for (int i = 0; i < n; ++i) out[i] = scope_[i].load(std::memory_order_relaxed);
+ if (n > S_Bank) out[S_Bank] = (float)bank_;
+ if (n > S_Rev) out[S_Rev] = (float)(rev_.load(std::memory_order_relaxed) & 0xFFFFFF);
return n;
}
@@ -182,7 +230,21 @@ public:
const double stepBeats = 0.25; // 1/16
int flash[kVoices] = {0};
- int lastStep = curStep_;
+ // Auditions from the editor (message thread → here, lock-free).
+ for (int v = 0; v < kVoices; ++v) {
+ float a = pendingTrig_[v].exchange(-1.0f, std::memory_order_relaxed);
+ if (a >= 0.0f) { trigger(v, a); flash[v] = 1; }
+ }
+ // Glue: a gentle feed-forward bus compressor on the kit sum (peak detector, 5 ms
+ // attack, 150 ms release) — threshold −8 → −24 dB and ratio 1.5 → 4 as Glue rises.
+ // The makeup follows 70 % of the average reduction (a ~0.7 s average), so the tails come
+ // up while the hits never end louder than they went in. 0 = out of circuit.
+ const float glue = get(Glue);
+ const bool glueOn = glue > 0.001f;
+ const float thrDb = -8.0f - glue * 16.0f, ratio = 1.5f + glue * 2.5f;
+ const float atk = std::exp(-1.0f / (0.005f * (float)sampleRate_)), rel = std::exp(-1.0f / (0.150f * (float)sampleRate_));
+ const float avgC = std::exp(-1.0f / (0.7f * (float)sampleRate_));
+ float grMax = 0.0f;
for (int32_t i = 0; i < frames; ++i) {
// --- sequencer clock ---
if (playing_ && spb_ > 0.0) {
@@ -219,22 +281,42 @@ public:
const float gr = (pan >= 0.0f ? 1.0f : 1.0f + pan);
l += s * gl; r += s * gr;
}
+ if (glueOn) {
+ const float pk = std::max(std::fabs(l), std::fabs(r));
+ const float lvlDb = pk > 1e-6f ? 20.0f * std::log10(pk) : -120.0f;
+ const float over = std::max(0.0f, lvlDb - thrDb);
+ const float target = over * (1.0f - 1.0f / ratio); // dB of reduction wanted
+ const float c = target > glueGr_ ? atk : rel;
+ glueGr_ = target + c * (glueGr_ - target);
+ glueAvg_ = glueGr_ + avgC * (glueAvg_ - glueGr_);
+ const float g = std::pow(10.0f, (std::min(glueAvg_ * 0.7f, glueGr_) - glueGr_) * 0.05f);
+ l *= g; r *= g;
+ grMax = std::max(grMax, glueGr_);
+ } else { glueGr_ = 0.0f; glueAvg_ = 0.0f; }
out[i * 2] += l * vol;
out[i * 2 + 1] += r * vol;
}
// publish telemetry
scope_[S_Step].store((float)(playing_ ? curStep_ : -1), std::memory_order_relaxed);
+ scope_[S_Glue].store(grMax, std::memory_order_relaxed);
+ int active = 0;
for (int v = 0; v < kVoices; ++v) {
float f = scope_[S_Flash0 + v].load(std::memory_order_relaxed) * 0.6f;
if (flash[v]) f = 1.0f;
scope_[S_Flash0 + v].store(f, std::memory_order_relaxed);
+ const Voice& vc = voices_[v];
+ if (vc.active) ++active;
+ float pos = -1.0f;
+ if (vc.active && vc.splay && smp_[v] && smp_[v]->frames > 0) pos = (float)(vc.spos / (double)smp_[v]->frames);
+ scope_[S_Pos0 + v].store(pos, std::memory_order_relaxed);
}
- (void)lastStep;
+ active_.store(active, std::memory_order_relaxed);
}
private:
- static constexpr uint32_t kMagic = 0x31485452; // "RTH1"
+ static constexpr uint32_t kMagicV1 = 0x31485452; // "RTH1" — 60 params
+ static constexpr uint32_t kMagic = 0x32485452; // "RTH2" — + sample region, Glue
static constexpr double kTwoPi = 6.283185307179586;
static constexpr const char* kVoiceNames[kVoices] = { "Kick", "Snare", "Clap", "Rim", "Closed Hat", "Open Hat", "Tom", "Perc" };
static constexpr int kMidiMap[kVoices] = { 36, 38, 39, 37, 42, 46, 45, 41 };
@@ -249,10 +331,13 @@ private:
float bp = 0.0f, bp2 = 0.0f; // band-pass (SVF) states
int burst = 0; float burstT = 0.0f; // clap multi-burst
double spos = 0.0; bool splay = false; // sample-voice playback
+ double sBeg = 0.0, sEnd = 0.0; bool srev = false; // the played region, direction
};
// --- helpers -----------------------------------------------------------
void setP(int v, int p, float val) { pn_[v * kPV + p].store(val, std::memory_order_relaxed); }
+ void setX(int v, int p, float val) { pn_[kExtra + v * kPX + p].store(val, std::memory_order_relaxed); }
+ float getX(int v, int p) const { return pn_[kExtra + v * kPX + p].load(std::memory_order_relaxed); }
float get(int i) const { return pn_[i].load(std::memory_order_relaxed); }
float get2(int v, int p) const { return pn_[v * kPV + p].load(std::memory_order_relaxed); }
static bool valid(int v, int s) { return v >= 0 && v < kVoices && s >= 0 && s < kSteps; }
@@ -269,6 +354,15 @@ private:
vc.burst = 0; vc.burstT = 0.0f;
vc.splay = (src_[v] == Sample && smp_[v] && !smp_[v]->empty());
vc.spos = 0.0; vc.lp = 0.0f;
+ if (vc.splay) {
+ // The played region: Start .. Start + Length of the file (at least ~1 ms); Reverse
+ // plays it back to front.
+ const double n = (double)smp_[v]->frames;
+ const double st = std::clamp((double)getX(v, Start), 0.0, 1.0) * n;
+ const double en = std::clamp(st + (double)getX(v, Length) * n, std::min(n, st + 48.0), n);
+ vc.sBeg = st; vc.sEnd = en; vc.srev = getX(v, Reverse) >= 0.5f;
+ vc.spos = vc.srev ? std::max(st, en - 1.0) : st;
+ }
if (v == 4) voices_[5].active = false; // closed hat chokes open hat (808)
}
@@ -281,13 +375,16 @@ private:
float l, r; b.readStereo((int64_t)vc.spos, l, r);
float s = 0.5f * (l + r);
const double rate = (b.sourceSampleRate > 0 ? b.sourceSampleRate / sampleRate_ : 1.0) * std::exp2((tune - 0.5) * 2.0);
- vc.spos += rate;
+ // A 64-frame fade into the region's far edge, so a Length cut never clicks.
+ const double left = vc.srev ? vc.spos - vc.sBeg : vc.sEnd - vc.spos;
+ if (left < 64.0 * rate) s *= (float)std::max(0.0, left / (64.0 * rate));
+ vc.spos += vc.srev ? -rate : rate;
// Tone as a gentle one-pole low-pass (0 = dark, 1 = open).
const float lpc = 0.05f + tone * 0.95f;
vc.lp += lpc * (s - vc.lp); s = vc.lp;
if (drive > 0.001f) s = std::tanh(s * (1.0f + drive * 3.0f));
vc.env *= decayCoef(expMap(decay, 0.05f, 2.0f));
- if (vc.spos >= (double)b.frames || (vc.env < 1e-4f)) { vc.active = false; vc.splay = false; }
+ if ((vc.srev ? vc.spos < vc.sBeg : vc.spos >= vc.sEnd) || vc.env < 1e-4f) { vc.active = false; vc.splay = false; }
return s * vc.env * vc.vel * get2(v, Level);
}
@@ -396,6 +493,11 @@ private:
std::shared_ptr<SampleBuffer> smp_[kVoices]; // per-voice sample (Phase 2); null = synth
uint8_t src_[kVoices] = {0}; // per-voice source: 0 Synth, 1 Sample
+ float glueGr_ = 0.0f, glueAvg_ = 0.0f; // glue gain reduction + its average, dB (audio thread)
+ std::atomic<float> pendingTrig_[kVoices]; // auditions waiting for render(), -1 = none
+ std::atomic<uint32_t> rev_{0}; // pattern edit revision (scope S_Rev)
+ std::atomic<int32_t> active_{0}; // sounding voices, last block
+
std::atomic<float> scope_[kScopeN];
std::atomic<float> pn_[kNumParams];
};
diff --git a/tests/Nota.SmokeTest/DesignTokenCheck.cs b/tests/Nota.SmokeTest/DesignTokenCheck.cs
index c9fcae2e..4d6ea87c 100644
--- a/tests/Nota.SmokeTest/DesignTokenCheck.cs
+++ b/tests/Nota.SmokeTest/DesignTokenCheck.cs
@@ -301,9 +301,8 @@ internal static class DesignTokenCheck
var app = Path.Combine(root, "src/managed/Nota.App");
var views = Directory.EnumerateFiles(Path.Combine(app, "Controls"), "*.cs")
.Select(f => (Path: Path.GetRelativePath(app, f), Text: File.ReadAllText(f))).ToArray();
- // Deliberate exceptions: MixBar is a level strip, not a graph window; RhythmWaveViz
- // draws the waveform itself as a shape, which is data, not a fill under a curve.
- var exempt = new HashSet<string> { "Controls/MixBar.cs", "Controls/RhythmWaveViz.cs" };
+ // Deliberate exception: MixBar is a level strip, not a graph window.
+ var exempt = new HashSet<string> { "Controls/MixBar.cs" };
string[] Offenders(string pattern) => views.Where(v => !exempt.Contains(v.Path) && Regex.IsMatch(v.Text, pattern)).Select(v => v.Path).OrderBy(p => p).ToArray();
var frames = Offenders(@"DrawRectangle\((?:Sunken|Bg|Well|NotaPalette\.BgSunken), (?:new Pen\(\w+(?:, 1)?\)|null), new Rect\(0, 0, w, h\), \d+, \d+\)");
@@ -384,9 +383,9 @@ internal static class DesignTokenCheck
yield return (Regex.IsMatch(kit, @"HeaderH = 22;"), "device card header is 22px");
// Accepted exceptions (decided 2026-09-16): plug-in / parameter stubs are narrow; the
- // Rhythm, Bass and Physical instruments keep their wider layouts.
+ // Bass and Physical instruments keep their wider layouts.
var exempt = new HashSet<string> { "PluginDeviceBody.cs", "GenericParamDeviceBody.cs", "GenericMidiBody.cs",
- "RhythmInstrumentCard.cs", "BassInstrumentCard.cs", "PhysicalInstrumentCard.cs" };
+ "BassInstrumentCard.cs", "PhysicalInstrumentCard.cs" };
var off = Directory.EnumerateFiles(Path.Combine(app, "DeviceCards"), "*.cs", SearchOption.AllDirectories)
.Where(f => !exempt.Contains(Path.GetFileName(f)))
.SelectMany(f => Regex.Matches(File.ReadAllText(f), @"public double (?:Card)?Width => (?<w>[0-9]+);")
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index af20f1dd..f251e7ef 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -10954,7 +10954,13 @@ Console.WriteLine("-- Nota Rhythm --");
Check(re.TrackInstrumentKind(t) == 12, $"instrument kind is 12 ({re.TrackInstrumentKind(t)})");
Check(re.DeviceName(t, -1) == "Nota Rhythm", $"name is Nota Rhythm ('{re.DeviceName(t, -1)}')");
int pc = re.PluginParamCount(t, -1);
- Check(pc == 60, $"param count 60 (got {pc})");
+ Check(pc == 85, $"param count 85 (got {pc})");
+ int RIdx(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; }
+ Check(re.PluginParamName(t, -1, RIdx(re, t, "v4_decay")) == "Closed Hat Decay" && re.PluginParamName(t, -1, RIdx(re, t, "swing")) == "Perform Swing"
+ && re.PluginParamName(t, -1, RIdx(re, t, "glue")) == "Master Glue" && re.PluginParamName(t, -1, RIdx(re, t, "v2_start")) == "Clap Start",
+ "Rhythm param names group by voice / Perform / Master (the automation menu heads)");
+ Check(Math.Abs(re.InstrumentParamDefault(t, RIdx(re, t, "v0_length")) - 1f) < 1e-4f && re.InstrumentParamDefault(t, RIdx(re, t, "glue")) == 0f,
+ "sample Length defaults to the whole file, Glue to off");
int kickTune = -1; for (int i = 0; i < pc; i++) if (re.PluginParamId(t, -1, i) == "v0_tune") kickTune = i;
Check(kickTune >= 0, "found v0_tune param");
@@ -10991,6 +10997,113 @@ Console.WriteLine("-- Nota Rhythm --");
re3.SetPluginState(t3, -1, blob);
int kt3 = -1; for (int i = 0; i < re3.PluginParamCount(t3, -1); i++) if (re3.PluginParamId(t3, -1, i) == "v0_tune") kt3 = i;
Check(kt3 >= 0 && Math.Abs(re3.PluginParamGet(t3, -1, kt3) - 0.9f) < 0.02f, "state blob restores params");
+
+ // An RTH1 blob (60 params, before the sample region and Glue) still loads: params, steps.
+ {
+ var v2 = re.GetPluginState(t, -1);
+ var v1 = new List<byte>();
+ v1.AddRange(BitConverter.GetBytes(0x31485452u));
+ v1.AddRange(v2.Skip(4).Take(60 * 4));
+ v1.AddRange(v2.Skip(4 + 85 * 4));
+ using var old = new NotaEngine();
+ int to = old.AddRhythmTrack();
+ old.InstrumentAction(to, 4, 0, 0); // clear, so the steps must come from the blob
+ old.SetPluginState(to, -1, v1.ToArray());
+ var op = RhythmModel.Parse(old.GetPluginState(to, -1), old.PluginParamCount(to, -1));
+ Check(Math.Abs(old.PluginParamGet(to, -1, RIdx(old, to, "v0_tune")) - 0.9f) < 0.02f && op.On[0, 0, 0] && op.On[0, 0, 4] && op.On[0, 4, 2]
+ && Math.Abs(old.PluginParamGet(to, -1, RIdx(old, to, "v0_length")) - 1f) < 1e-4f,
+ "an RTH1 blob (older projects) restores params and steps; new params keep defaults");
+ var legacy = RhythmModel.Parse(v1.ToArray(), 85);
+ Check(legacy.On[0, 0, 0] && legacy.On[0, 4, 2] && !legacy.On[0, 1, 0], "RhythmModel.Parse reads an RTH1 blob");
+ }
+
+ // The editing channel: copy a bank, clear a voice, the edit revision + bank in the scope.
+ {
+ var sc = new float[RhythmModel.ScopeLength];
+ int n0 = re.InstrumentScope(t, sc);
+ float rev0 = sc[RhythmModel.S_Rev];
+ re.InstrumentAction(t, RhythmModel.A_CopyBank, 0 * 4 + 2, 0); // A → C
+ re.InstrumentAction(t, RhythmModel.A_SelectBank, 2, 0);
+ re.InstrumentScope(t, sc);
+ var cp = RhythmModel.Parse(re.GetPluginState(t, -1), pc);
+ Check(n0 == RhythmModel.ScopeLength && sc[RhythmModel.S_Rev] != rev0 && (int)sc[RhythmModel.S_Bank] == 2 && cp.CurrentBank == 2
+ && cp.On[2, 0, 0] && cp.On[2, 0, 12] && cp.On[2, 4, 2], $"copy bank A → C, select C; the scope reports the bank and a new edit revision ({n0} floats)");
+ re.InstrumentAction(t, RhythmModel.A_ClearVoice, 0, 0);
+ cp = RhythmModel.Parse(re.GetPluginState(t, -1), pc);
+ Check(cp.Count(2, 0) == 0 && cp.Count(0, 0) == 4 && cp.On[2, 4, 2], "clear voice empties only that voice in the current bank");
+ re.InstrumentAction(t, RhythmModel.A_SelectBank, 0, 0);
+ }
+
+ // Audition plays a voice with the transport stopped; the sounding count follows.
+ {
+ using var ae = new NotaEngine();
+ int ta = ae.AddRhythmTrack();
+ ae.InstrumentAction(ta, RhythmModel.A_Audition, 1, 0.9f); // snare
+ var ab = new float[4096 * 2];
+ ae.RenderOffline(ab, 4096);
+ Check(Rms(ab, 4096) > 0.001f && ab.All(float.IsFinite), $"audition plays a voice with the transport stopped ({Rms(ab, 4096):F3})");
+ Check(ae.InstrumentVoiceCount(ta) >= 1, $"the sounding-voice count sees it ({ae.InstrumentVoiceCount(ta)})");
+ }
+
+ // Glue: the bus compressor pulls the loud kit down (the makeup is only 70 % of the average
+ // reduction), never makes a hit louder than it went in, and stays finite.
+ {
+ (float Rms, float Peak) Kit(float glueV)
+ {
+ using var ge = new NotaEngine();
+ ge.SetBpm(120); ge.SetTimeSignature(4, 4);
+ int tg = ge.AddRhythmTrack();
+ ge.PluginParamSet(tg, -1, RIdx(ge, tg, "glue"), glueV);
+ ge.PluginParamSet(tg, -1, RIdx(ge, tg, "v0_drive"), 1f);
+ ge.PluginParamSet(tg, -1, RIdx(ge, tg, "v0_level"), 1f);
+ var gb = new float[44100 * 2];
+ ge.Seek(0); ge.Play(); ge.RenderOffline(gb, 44100); ge.StopTransport();
+ if (!gb.All(float.IsFinite)) return (float.NaN, float.NaN);
+ float r = Rms(gb, 44100);
+ return (r, gb.Max(Math.Abs));
+ }
+ var dry = Kit(0f); var glued = Kit(1f);
+ Check(float.IsFinite(glued.Rms) && glued.Rms > 0.001f && glued.Rms < dry.Rms * 0.9f && glued.Peak <= dry.Peak * 1.02f,
+ $"Glue compresses the kit (RMS {dry.Rms:F3} → {glued.Rms:F3}, peak {dry.Peak:F2} → {glued.Peak:F2})");
+ }
+
+ // Factory kits: ≥ 25, every id exists, each plays the pattern finite and unclipped; a kit
+ // keeps the steps and a voice's sample region; a user kit can be saved.
+ {
+ var ids = new HashSet<string>();
+ for (int i = 0; i < pc; i++) ids.Add(re.PluginParamId(t, -1, i));
+ var cat = new FactoryPresetCatalog();
+ var mine = cat.All().Where(p => p.IsInstrument && p.BuiltinKind == 12).ToList();
+ Check(mine.Count >= 25, $"Nota Rhythm ships ≥ 25 factory kits (got {mine.Count})");
+ var bad = mine.SelectMany(p => cat.Document(p.Id)!.NamedParams!.Keys.Where(k => !ids.Contains(k)).Select(k => $"{p.DisplayName}:{k}")).ToList();
+ Check(bad.Count == 0, $"every Rhythm kit param id exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");
+ var quiet = new List<string>();
+ foreach (var p in mine)
+ {
+ using var ep = new NotaEngine();
+ ep.SetBpm(120); ep.SetTimeSignature(4, 4);
+ int tp = ep.AddRhythmTrack();
+ if (cat.ApplyInPlace(ep, p.Id, tp, -1).Length != 0) { quiet.Add($"{p.DisplayName} (apply)"); continue; }
+ var pb = new float[44100 * 2 * 2];
+ ep.Seek(0.0); ep.Play(); ep.RenderOffline(pb, 44100 * 2); ep.StopTransport();
+ float r = Rms(pb, 44100 * 2), pk = pb.Max(Math.Abs);
+ if (!pb.All(float.IsFinite) || r < 0.003f || pk > 2f) quiet.Add($"{p.DisplayName} ({r:F3}/{pk:F2})");
+ }
+ Check(quiet.Count == 0, $"every Rhythm kit plays its pattern, finite and not clipping hard{(quiet.Count > 0 ? " — " + string.Join(", ", quiet) : "")}");
+
+ using var kp = new NotaEngine();
+ int tk = kp.AddRhythmTrack();
+ kp.PluginParamSet(tk, -1, RIdx(kp, tk, "v2_length"), 0.4f);
+ kp.InstrumentAction(tk, RhythmModel.A_ToggleStep, 1 * 16 + 3, 0); // snare on step 4
+ string trap = mine.First(p => p.DisplayName == "Trap").Id;
+ cat.ApplyInPlace(kp, trap, tk, -1);
+ var kpat = RhythmModel.Parse(kp.GetPluginState(tk, -1), kp.PluginParamCount(tk, -1));
+ Check(kpat.On[0, 1, 3] && kpat.On[0, 0, 0] && Math.Abs(kp.PluginParamGet(tk, -1, RIdx(kp, tk, "v2_length")) - 0.4f) < 1e-4f
+ && Math.Abs(kp.PluginParamGet(tk, -1, RIdx(kp, tk, "v0_tune")) - 0.1f) < 1e-4f,
+ "applying a kit sets the sound and keeps the steps and the sample region");
+ var user = PresetService.Capture(kp, tk, -1, "My Kit");
+ Check(user is { Type: "builtin-instrument", BuiltinKind: 12 } && user.NamedParams!.ContainsKey("glue"), "a Rhythm kit can be saved as a user preset");
+ }
}
// ============ Nota Rhythm — per-voice samples (Phase 2) ==================
@@ -11013,10 +11126,45 @@ Console.WriteLine("-- Nota Rhythm samples --");
Check(se.RhythmVoiceSource(t, 0) == 0, "toggle voice 0 back to Synth");
se.InstrumentAction(t, 6, 0, 1f); // → Sample again (buffer still present)
Check(se.RhythmVoiceSource(t, 0) == 1, "toggle voice 0 back to Sample");
+ Check(se.TryGetRhythmVoiceInfo(t, 0, out var ni) && se.SampleName(ni.SampleId) == Path.GetFileNameWithoutExtension(smpWav), "the voice sample keeps its file name");
+
+ // The sample region: a short Length plays less; Reverse still plays; the scope reports
+ // the play position while it sounds.
+ {
+ float Region(float start, float length, bool reverse)
+ {
+ using var ge = new NotaEngine();
+ int tg = ge.AddRhythmTrack();
+ ge.SetRhythmVoiceSample(tg, 0, smpWav);
+ int pcg = ge.PluginParamCount(tg, -1);
+ for (int i = 0; i < pcg; i++)
+ {
+ string id = ge.PluginParamId(tg, -1, i);
+ if (id == "v0_start") ge.PluginParamSet(tg, -1, i, start);
+ if (id == "v0_length") ge.PluginParamSet(tg, -1, i, length);
+ if (id == "v0_reverse") ge.PluginParamSet(tg, -1, i, reverse ? 1f : 0f);
+ if (id == "v0_decay") ge.PluginParamSet(tg, -1, i, 1f);
+ }
+ ge.InstrumentAction(tg, RhythmModel.A_Audition, 0, 1f);
+ var gb = new float[22050 * 2];
+ ge.RenderOffline(gb, 512);
+ var sc = new float[RhythmModel.ScopeLength];
+ ge.InstrumentScope(tg, sc);
+ float pos = sc[RhythmModel.S_Pos0];
+ ge.RenderOffline(gb, 22050);
+ float energy = 0; foreach (var x in gb) energy += x * x;
+ return reverse ? (pos > start ? energy : -1) : (pos >= start && pos < start + 0.2f ? energy : -1);
+ }
+ float full = Region(0, 1, false), cut = Region(0, 0.2f, false), rev = Region(0.2f, 0.6f, true);
+ Check(full > 0 && cut > 0 && cut < full * 0.5f, $"a short sample Length plays less of the file ({full:F1} vs {cut:F1})");
+ Check(rev > 0, $"a reversed region plays, and the scope tracks its position ({rev:F1})");
+ }
string dir = Path.Combine(Path.GetTempPath(), "nota-rhythm-proj-" + Guid.NewGuid().ToString("N"));
try
{
+ se.SetRhythmVoiceSample(t, 1, smpWav);
+ se.InstrumentAction(t, RhythmModel.A_SetSource, 1, 0f); // voice 1 keeps a sample but plays the synth
var w = new System.Collections.Generic.List<string>();
var doc = ProjectService.Capture(se, new TransportState(120, 1, false, false), w);
ProjectService.Save(doc, dir, se);
@@ -11026,6 +11174,8 @@ Console.WriteLine("-- Nota Rhythm samples --");
int dt = -1; for (int i = 0; i < de.TrackCount; i++) if (de.TryGetTrackInfo(i, out var ti) && ti.IsInstrument && de.TrackInstrumentKind(ti.Id) == 12) dt = ti.Id;
Check(dt > 0 && de.RhythmVoiceSource(dt, 0) == 1, "round-trip restores voice 0 as Sample");
Check(de.TryGetRhythmVoiceInfo(dt, 0, out var dvi) && dvi.SampleId != 0, "round-trip restores the voice sample");
+ Check(de.RhythmVoiceSource(dt, 1) == 0 && de.TryGetRhythmVoiceInfo(dt, 1, out var dv1) && dv1.SampleId != 0,
+ "round-trip keeps a sample on a voice that plays its synth (and keeps it on Synth)");
}
finally { try { if (Directory.Exists(dir)) Directory.Delete(dir, true); } catch { } }
}
@@ -11250,6 +11400,21 @@ Console.WriteLine("-- MCP tools --");
mcpRhythm.SetRhythmStep(mcpRhy, 0, 4, false).Wait();
var mcpKick2 = Array.Find(mcpRhythm.GetRhythm(mcpRhy, 0).Result.Voices, v => v.Index == 0);
Check(mcpKick2!.Steps.Length == 3 && !Array.Exists(mcpKick2.Steps, s => s.Index == 4), "MCP set_rhythm_step off removes the step");
+ // Text rows, voice / groove shaping, bank copy.
+ string mcpPat = mcpRhythm.SetRhythmPattern(mcpRhy, new Dictionary<string, string> { ["snare"] = "....X.......x..o", ["ch"] = "x.x.x.x.|x.x.x.xo" }).Result;
+ var mcpSnap2 = mcpRhythm.GetRhythm(mcpRhy).Result;
+ Check(!mcpPat.StartsWith("error") && mcpSnap2.Voices[1].Pattern == "....X.......x..o" && mcpSnap2.Voices[4].Pattern == "x.x.x.x.x.x.x.xo"
+ && mcpSnap2.Voices[1].Steps.Length == 3 && mcpSnap2.Voices[1].Steps[0].Accent && mcpSnap2.Voices[1].Steps[2].Velocity < 0.45f,
+ $"MCP set_rhythm_pattern writes text rows (x on · X accent · o quiet) ({mcpPat})");
+ Check(mcpRhythm.SetRhythmPattern(mcpRhy, new Dictionary<string, string> { ["cowbell"] = "x..." }).Result.StartsWith("error"), "MCP set_rhythm_pattern names what it cannot read");
+ string mcpVoice = mcpRhythm.SetRhythmVoice(mcpRhy, "kick", tune: 0.1f, decay: 0.9f, level: 0.95f).Result;
+ string mcpPerf = mcpRhythm.SetRhythmPerform(mcpRhy, swing: 0.25f, glue: 0.4f).Result;
+ var mcpSnap3 = mcpRhythm.GetRhythm(mcpRhy).Result;
+ Check(mcpVoice.StartsWith("Kick") && Math.Abs(mcpSnap3.Voices[0].Sound!.Decay - 0.9f) < 1e-3f && Math.Abs(mcpSnap3.Swing - 0.25f) < 1e-3f
+ && Math.Abs(mcpSnap3.Glue - 0.4f) < 1e-3f && mcpPerf.Contains("glue 40") && mcpSnap3.Guide.Contains("glue") && mcpSnap3.Summary.Length > 0,
+ $"MCP set_rhythm_voice / set_rhythm_perform shape the kit ({mcpVoice} | {mcpPerf})");
+ Check(mcpRhythm.CopyRhythmBank(mcpRhy, 0, 3).Result.StartsWith("copied") && mcpRhythm.GetRhythm(mcpRhy, 3).Result.Voices[1].Pattern == "....X.......x..o",
+ "MCP copy_rhythm_bank copies A to D");
// ---- MIDI controllers + MIDI Learn over MCP ----
var mcpMidiDevSvc = new Nota.Infrastructure.MidiDeviceService();