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 Synth

Egor Khindikaynend551c93e4f64
diff --git a/.claude/skills/nota-instrument/SKILL.md b/.claude/skills/nota-instrument/SKILL.md
index 6e4d45ff..06372920 100644
--- a/.claude/skills/nota-instrument/SKILL.md
+++ b/.claude/skills/nota-instrument/SKILL.md
@@ -161,6 +161,12 @@ Follow the mockup language:
shell header; the toggle writes `View` and calls `ctx.RequestRebuild()`. Per-card UI
state that should survive the rebuild (active tab, selected lane) lives in a static map
keyed by (track, index), not in the singleton body.
+ - Plumbing (instruments, Nota Synth is the reference): append a `"view"` plugin param to the
+ DSP (its default in the constructor is the instrument's default size — Synth opens as S);
+ `InstrumentView` (Nota.Application) finds/reads/writes it, and presets, A/B, the automation
+ menu (by id) and the rack chain card (by the name "View") already skip it. The card implements
+ `IInstrumentCard.WidthFor(engine, track)` + `HeaderAccessory(ctx)` with
+ `MidiCardHeader.SizeToggle(ctx, isMini, setMini)`; the shell goes compact under 300px.
- **Lay panels as a signal chain**: bordered titled sections left→right with `▸`
arrows (Osc → Noise → Filter → Amp). Each panel = `Border` (SurfaceCard fill,
1px border, radius 7) with a bold section title.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0f4b99d1..d32521f8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -91,6 +91,20 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
- Nota Scale has 35 presets. The automation menu lists its settings, and each note of the
Custom scale is under Custom Notes. MCP gets new tools for it: `get_scale`, `set_scale`
and `set_scale_note`.
+- Nota Velocity has a new look in the same two sizes, a full card and a small 260-pixel one.
+ The TRANSFER graph shows the curve, the band Random can move a note within, the Out range
+ as dashed lines and the last 12 notes as dots. Each new note pops in, and the curve glides
+ to its new shape when you change a setting. LAST 12 NOTES shows each note's velocity in as
+ an outline and out as a fill.
+- Nota Velocity's Random has its own on/off switch, so you can turn it off without losing
+ the amount. Random goes up to ±64. Drive now goes from 0.25 to 4 (it stopped at 2). A note
+ never comes out at velocity 0. Projects and presets from older versions sound the same.
+- Nota Velocity has 32 presets. The automation menu lists its settings, and MCP gets new
+ tools for it: `get_velocity` and `set_velocity`.
+- Nota Synth now comes in two sizes too: the full card and a small 260-pixel one with the
+ filter curve and four knobs (Cutoff, Reso, Attack, Release). Switch with S / L in the card's
+ header. A new Synth opens small. The project remembers each Synth's size, and presets
+ don't change it.
### Fixed
- Nota Scale no longer leaves notes hanging when you change the scale, root or fold while a
diff --git a/FEATURES.md b/FEATURES.md
index f453cecc..4582c53c 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -256,7 +256,9 @@ and user presets, automation, persistence and cloning.
(Saw/Square/Triangle/Sine) with pulse width, detune, octave and a 1/2/4/7-voice unison
stack with stereo spread; ADSR; a filter with type Off/LP/HP/BP, resonance and an
Env → Cutoff amount; voice modes Poly 16 / Mono / Legato with glide, pan and Vel→Vol.
- Osc · Env · Filter tabs with draggable envelope and filter graphs. 25 factory presets.
+ Osc · Env · Filter tabs with draggable envelope and filter graphs. Two sizes (L 700 /
+ S 260, S by default): S is the draggable filter curve over Cutoff · Reso · Attack ·
+ Release; the size is saved with the project. 25 factory presets.
- **Nota Sampler** — sampler (one-shot and loop: Off / Fwd / Ping / Rev), voice modes
Poly 16 / Mono / Choke, Glide (legato in Mono), loop crossfade, sample Gain, pitch
Keytrack, filter key-tracking and Env → Cutoff, Vel→Vol, Output; Sample · Pitch · Env ·
@@ -544,8 +546,11 @@ and user presets, automation, persistence and cloning.
limit (the bar line). Two sizes (L 700 / S 260) with an animated GATE window: one bar of five
notes, input outlined, output filled, Random's range as a band. 32 presets, full
automation, MCP tools (`get_length` / `set_length`).
-- **Nota Velocity** — velocity transformation: Curve/Compand/Fixed, Drive, Random, Out
- Range, Random Dir, and a Last 12 histogram.
+- **Nota Velocity** — velocity transformation: Curve / Compand / Fixed, Drive (0.25 … 4) or
+ the Fixed value, Out range (1 … 127, never 0), Random ±0 … 64 with its own switch and Both /
+ Up / Down. Two sizes (L 700 / S 260) with an animated TRANSFER graph (curve, Random's band,
+ the last 12 notes as dots) and a LAST 12 NOTES histogram (in outlined, out filled). 32
+ presets, full automation, MCP tools (`get_velocity` / `set_velocity`).
- **Nota Random** — randomization: Chance; Note (±12 st) / Velocity (±64) / Timing (up to
100 ms late) / Skip / Octave (±2) amounts; Gauss / Even / Walk; Per note / Per bar; Stay in
scale (C major); seed with Reroll and Lock (holds the roll on screen, repeating it every bar).
diff --git a/src/managed/Nota.App/ArrangementView.Automation.cs b/src/managed/Nota.App/ArrangementView.Automation.cs
index 00a762a0..44f5fc8b 100644
--- a/src/managed/Nota.App/ArrangementView.Automation.cs
+++ b/src/managed/Nota.App/ArrangementView.Automation.cs
@@ -522,6 +522,22 @@ public sealed partial class ArrangementView
};
foreach (var (p, label) in ps) mMenu.Items.Add(MLeaf(m, p, label));
}
+ else if (e.MidiEffectKind(t.Id, m) == 4 && mpc > VelocityModel.PView)
+ {
+ // Nota Velocity: MODE, then OUT RANGE / RANDOM. View (the card size) is editor state.
+ (int p, string label)[] ps =
+ {
+ (VelocityModel.PMode, "Mode"), (VelocityModel.PDrive, "Drive"), (VelocityModel.PFixed, "Value (Fixed)"),
+ };
+ foreach (var (p, label) in ps) mMenu.Items.Add(MLeaf(m, p, label));
+ mMenu.Items.Add(new Separator());
+ (int p, string label)[] outs =
+ {
+ (VelocityModel.POutLo, "Out Low"), (VelocityModel.POutHi, "Out High"),
+ (VelocityModel.PRandomOn, "Random On"), (VelocityModel.PRandom, "Random"), (VelocityModel.PRandomDir, "Random Direction"),
+ };
+ foreach (var (p, label) in outs) mMenu.Items.Add(MLeaf(m, p, label));
+ }
else if (e.MidiEffectKind(t.Id, m) == 5 && mpc > RandomModel.PLockBar)
{
// Nota Random: WHAT VARIES, then DICE. View (the card size) and Lock Bar (set by
@@ -606,7 +622,7 @@ public sealed partial class ArrangementView
{
string id = e.PluginParamId(t.Id, -1, i);
string nm = e.PluginParamName(t.Id, -1, i);
- if (id.Length == 0) continue;
+ if (id.Length == 0 || InstrumentView.IsViewParam(id)) continue; // the card size isn't sound
string grp = Head(nm);
if (grp.Length > 0 && sizes[grp] < 2) grp = "";
string leaf = grp.Length > 0 ? nm[(grp.Length + 1)..] : nm;
diff --git a/src/managed/Nota.App/Controls/RangeSliderTrack.cs b/src/managed/Nota.App/Controls/RangeSliderTrack.cs
new file mode 100644
index 00000000..26983b56
--- /dev/null
+++ b/src/managed/Nota.App/Controls/RangeSliderTrack.cs
@@ -0,0 +1,133 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// A two-handle range slider in the almanac slider look (SliderTrack): a 3px well-colour
+// track, a brass fill between the handles and two 6×7 Brass Light handles. Works in
+// normalised 0..1 (the caller maps to its units and keeps a minimum gap). A press picks the
+// nearer handle and a horizontal drag moves it by the pointer's travel — a click never jumps
+// a value; Shift (or Ctrl/⌘) drags fine. Double-click resets. GestureBegin / GestureEnd
+// (with the handle: 0 = low, 1 = high) bracket the drag for automation writes.
+
+using System;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+
+namespace Nota.App;
+
+internal sealed class RangeSliderTrack : Control
+{
+ private static readonly IBrush Groove = NotaPalette.BgSunken;
+ private static readonly IBrush Fill = NotaPalette.Accent;
+ private static readonly IBrush Handle = NotaPalette.AccentBright;
+ private static readonly IBrush HandleIdle = NotaPalette.TextSecondary;
+
+ private const double TrackH = 3, HandleW = 6, HandleH = 7;
+
+ private double _lo, _hi = 1, _lastX;
+ private int _drag = -1, _hover = -1;
+
+ public double Lo { get => _lo; set { value = Math.Clamp(value, 0, 1); if (value == _lo) return; _lo = value; InvalidateVisual(); } }
+ public double Hi { get => _hi; set { value = Math.Clamp(value, 0, 1); if (value == _hi) return; _hi = value; InvalidateVisual(); } }
+
+ /// <summary>Double-click handler (restore the defaults). Null disables double-click.</summary>
+ public Action? Reset { get; init; }
+
+ /// <summary>A handle moved: (handle 0 = low / 1 = high, its proposed 0..1 position).</summary>
+ public event Action<int, double>? Changed;
+ public event Action<int>? GestureBegin;
+ public event Action<int>? GestureEnd;
+
+ public bool Dragging => _drag >= 0;
+
+ public RangeSliderTrack()
+ {
+ Height = 12;
+ MinWidth = 40;
+ Cursor = new Cursor(StandardCursorType.SizeWestEast);
+ VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center;
+ }
+
+ private int Nearer(double x)
+ {
+ double w = Math.Max(1, Bounds.Width), dl = Math.Abs(x - _lo * w), dh = Math.Abs(x - _hi * w);
+ return dl < dh || (dl == dh && x < _lo * w) ? 0 : 1;
+ }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ if (e.ClickCount == 2 && Reset is not null)
+ {
+ if (_drag >= 0) { int d = _drag; _drag = -1; e.Pointer.Capture(null); GestureEnd?.Invoke(d); }
+ Reset();
+ e.Handled = true;
+ return;
+ }
+ _lastX = e.GetPosition(this).X;
+ _drag = Nearer(_lastX);
+ e.Pointer.Capture(this);
+ GestureBegin?.Invoke(_drag);
+ InvalidateVisual();
+ e.Handled = true;
+ }
+
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ double x = e.GetPosition(this).X;
+ if (_drag < 0)
+ {
+ int h = IsPointerOver ? Nearer(x) : -1;
+ if (h != _hover) { _hover = h; InvalidateVisual(); }
+ return;
+ }
+ double dx = x - _lastX;
+ _lastX = x;
+ if (dx == 0) return;
+ bool fine = (e.KeyModifiers & (KeyModifiers.Shift | KeyModifiers.Control | KeyModifiers.Meta)) != 0;
+ double cur = _drag == 0 ? _lo : _hi;
+ double v = Math.Clamp(cur + dx / Math.Max(1, Bounds.Width) * (fine ? 0.1 : 1), 0, 1);
+ if (Math.Abs(v - cur) < 1e-9) return;
+ Changed?.Invoke(_drag, v);
+ }
+
+ protected override void OnPointerExited(PointerEventArgs e)
+ {
+ base.OnPointerExited(e);
+ if (_hover != -1) { _hover = -1; InvalidateVisual(); }
+ }
+
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ if (_drag < 0) return;
+ int d = _drag; _drag = -1;
+ e.Pointer.Capture(null);
+ GestureEnd?.Invoke(d);
+ InvalidateVisual();
+ }
+
+ protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e)
+ {
+ if (_drag >= 0) { int d = _drag; _drag = -1; GestureEnd?.Invoke(d); }
+ base.OnPointerCaptureLost(e);
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ ctx.FillRectangle(Brushes.Transparent, new Rect(0, 0, w, h));
+ double cy = h / 2, ty = cy - TrackH / 2;
+ ctx.DrawRectangle(Groove, null, new RoundedRect(new Rect(0, ty, w, TrackH), NotaRadius.ClipValue));
+ double a = _lo * w, b = _hi * w;
+ if (b - a > 0.5) ctx.DrawRectangle(Fill, null, new RoundedRect(new Rect(a, ty, b - a, TrackH), NotaRadius.ClipValue));
+ for (int k = 0; k < 2; k++)
+ {
+ double x = k == 0 ? a : b;
+ double hx = Math.Clamp(x, HandleW / 2, w - HandleW / 2) - HandleW / 2;
+ bool hot = _drag == k || _hover == k;
+ ctx.DrawRectangle(hot ? Handle : HandleIdle, null, new RoundedRect(new Rect(hx, cy - HandleH / 2, HandleW, HandleH), NotaRadius.ClipValue));
+ }
+ }
+}
diff --git a/src/managed/Nota.App/Controls/SynthViz.cs b/src/managed/Nota.App/Controls/SynthViz.cs
index 3ce274e5..ebd346e1 100644
--- a/src/managed/Nota.App/Controls/SynthViz.cs
+++ b/src/managed/Nota.App/Controls/SynthViz.cs
@@ -9,6 +9,9 @@
// Filter the response curve for the chosen type, a drag pad for cutoff (X) / reso (Y),
// with the envelope's reach on the cutoff drawn as a teal ghost
//
+// Filter also draws the mini (S) card's one graph (Mini = true): no Hz axis, a soft brass
+// wash under the curve, and the captions cut to "LP · Saw" and the cutoff in brass.
+//
// All three read the engine's normalized params straight and denormalise them with the
// exact maps Synth.h uses, so the scales are real. Drawn through NotaGraph — well ground,
// hairline frame, corner axis labels, no fills under curves.
@@ -43,6 +46,9 @@ internal sealed class SynthViz : Control, IMidiLearnRegions
private readonly Dictionary<string, int> _idx;
private int _drag = -1; // Env: 0 attack · 1 decay/sustain · 2 release. Filter: 0 pad.
+ /// <summary>The mini (S) card's filter window: short captions, no axis, a wash under the curve.</summary>
+ public bool Mini { get; init; }
+
public SynthViz(K k, IAudioEngine engine, int track, Dictionary<string, int> idx)
{
_k = k; _e = engine; _t = track; _idx = idx;
@@ -73,7 +79,7 @@ internal sealed class SynthViz : Control, IMidiLearnRegions
private int FilType() => Math.Clamp((int)Math.Round(G("filtype") * 3), 0, 3);
private (double x0, double x1, double top, double bot) Geo()
- => (Pad, Math.Max(Pad + 1, Bounds.Width - Pad), Pad + 11, Math.Max(Pad + 12, Bounds.Height - Pad - 9));
+ => (Pad, Math.Max(Pad + 1, Bounds.Width - Pad), Pad + 11, Math.Max(Pad + 12, Bounds.Height - Pad - (Mini ? 0 : 9)));
private void Text(DrawingContext ctx, string t, double x, double y, IBrush ink, double size = 8)
=> ctx.DrawText(new FormattedText(t, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, size, ink), new Point(x, y));
@@ -191,6 +197,8 @@ internal sealed class SynthViz : Control, IMidiLearnRegions
}
private static readonly string[] WaveWords = { "saw", "square", "triangle", "sine" };
+ private static readonly string[] WaveNames = { "Saw", "Square", "Triangle", "Sine" };
+ private static readonly IBrush Wash = NotaPalette.Wash(NotaPalette.Accent, 0x18);
private void RenderOsc(DrawingContext ctx, double x0, double x1, double top, double bot)
{
@@ -285,8 +293,8 @@ internal sealed class SynthViz : Control, IMidiLearnRegions
if (type == 0)
{
ctx.DrawLine(new Pen(NotaPalette.BorderStrong, NotaGraph.PrimaryWidth), new Point(x0, flatY), new Point(x1, flatY));
- Text(ctx, "filter off · signal passes", x0 + 1, Pad - 3, TextTertiary);
- HzAxis(ctx, x0, x1, bot);
+ Text(ctx, Mini ? $"Off · {WaveNames[Wave()]}" : "filter off · signal passes", x0 + 1, Pad - 3, TextTertiary);
+ if (!Mini) HzAxis(ctx, x0, x1, bot);
return;
}
@@ -297,6 +305,7 @@ internal sealed class SynthViz : Control, IMidiLearnRegions
double modCut = Math.Clamp(cut + env * 4.0 / Math.Log2(18000.0 / 20.0), 0, 1);
DrawCurve(ctx, x0, x1, top, bot, modCut, res, type, NotaGraph.SecondaryPen(Teal, NotaGraph.SecondaryWidth));
}
+ if (Mini) DrawCurve(ctx, x0, x1, top, bot, cut, res, type, null, Wash);
DrawCurve(ctx, x0, x1, top, bot, cut, res, type, new Pen(Brass, NotaGraph.PrimaryWidth, lineJoin: PenLineJoin.Round));
double cx = x0 + cut * span;
@@ -305,6 +314,13 @@ internal sealed class SynthViz : Control, IMidiLearnRegions
double hz = ExpMap(cut, 20, 18000);
string[] names = { "Off", "LP", "HP", "BP" };
+ if (Mini)
+ {
+ Text(ctx, $"{names[type]} · {WaveNames[Wave()]}", x0 + 1, Pad - 3, TextTertiary);
+ string hzs = NotaNum.Hz(hz);
+ Text(ctx, hzs, x1 - 1 - MeasureW(hzs), Pad - 3, NotaPalette.AccentBright);
+ return;
+ }
Text(ctx, $"{names[type]} 12 dB/oct · {NotaNum.Hz(hz)} · Q {res.ToString("0.00", NotaNum.Culture)}", x0 + 1, Pad - 3, TextTertiary);
if (Math.Abs(env) > 0.01)
{
@@ -318,9 +334,10 @@ internal sealed class SynthViz : Control, IMidiLearnRegions
private static double CurveTop(double top, double bot, double res)
{ double flat = top + (bot - top) * 0.34; return Math.Max(top + 2, flat - res * (flat - top) * 0.92); }
- // The magnitude curve as a polyline, by filter type (1 LP · 2 HP · 3 BP).
+ // The magnitude curve as a polyline, by filter type (1 LP · 2 HP · 3 BP). With a
+ // `fill`, the area under it down to the floor instead (the mini card's wash).
private static void DrawCurve(DrawingContext ctx, double x0, double x1, double top, double bot,
- double cut, double res, int type, IPen pen)
+ double cut, double res, int type, IPen? pen, IBrush? fill = null)
{
double span = x1 - x0, cx = x0 + cut * span;
double flatY = top + (bot - top) * 0.34;
@@ -334,7 +351,20 @@ internal sealed class SynthViz : Control, IMidiLearnRegions
case 3: p.Add(new(x0, bot)); p.Add(new(kx, mid)); p.Add(new(cx, peakY)); p.Add(new(rx, mid)); p.Add(new(x1, bot)); break;
default: p.Add(new(x0, flatY)); p.Add(new(kx, flatY)); p.Add(new(cx, peakY)); p.Add(new((cx + x1) / 2, mid)); p.Add(new(x1, bot)); break;
}
- for (int i = 1; i < p.Count; i++) ctx.DrawLine(pen, p[i - 1], p[i]);
+ if (fill is not null)
+ {
+ var geo = new StreamGeometry();
+ using (var g = geo.Open())
+ {
+ g.BeginFigure(new Point(x0, bot), true);
+ foreach (var pt in p) g.LineTo(pt);
+ g.LineTo(new Point(x1, bot));
+ g.EndFigure(true);
+ }
+ ctx.DrawGeometry(fill, null, geo);
+ return;
+ }
+ for (int i = 1; i < p.Count; i++) ctx.DrawLine(pen!, p[i - 1], p[i]);
}
private void HzAxis(DrawingContext ctx, double x0, double x1, double bot)
diff --git a/src/managed/Nota.App/Controls/VelocityCurveViz.cs b/src/managed/Nota.App/Controls/VelocityCurveViz.cs
deleted file mode 100644
index c961184d..00000000
--- a/src/managed/Nota.App/Controls/VelocityCurveViz.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
-//
-// Nota Velocity transfer curve (mockup 3b): input velocity (x) → output velocity (y), with a
-// dashed identity diagonal, the brass transfer curve, teal dots for the last few notes' in→out
-// points (showing the random spread) and a bright dot for the most recent note.
-
-using System;
-using System.Collections.Generic;
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Media;
-
-namespace Nota.App;
-
-internal sealed class VelocityCurveViz : Control
-{
- private static readonly IBrush GridB = NotaGraph.Grid;
- private static readonly IBrush Ident = NotaPalette.SurfaceRaised;
- private static readonly IBrush Brass = NotaPalette.Accent;
- private static readonly IBrush Teal = NotaPalette.Wash(NotaPalette.Teal, 0x80);
- private static readonly IBrush Bright = NotaPalette.AccentBright;
- private static readonly IBrush Ink = NotaPalette.BgSunken;
-
- private Func<double, double>? _f;
- private readonly List<(double x, double y)> _dots = new();
- private (double x, double y)? _last;
-
- public VelocityCurveViz() { MinHeight = 60; }
-
- public void Set(Func<double, double> f, IReadOnlyList<(double inN, double outN)> dots, (double inN, double outN)? last)
- {
- _f = f;
- _dots.Clear(); foreach (var d in dots) _dots.Add(d);
- _last = last;
- InvalidateVisual();
- }
-
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height;
- if (w <= 0 || h <= 0 || _f is null) return;
- Point P(double xn, double yn) => new(xn * w, (1 - yn) * h);
-
- // Grid: centre cross-hair.
- ctx.DrawLine(new Pen(GridB, 1), new Point(0, h / 2), new Point(w, h / 2));
- ctx.DrawLine(new Pen(GridB, 1), new Point(w / 2, 0), new Point(w / 2, h));
- // Identity diagonal (dashed).
- ctx.DrawLine(new Pen(Ident, 1, dashStyle: new DashStyle(new double[] { 3, 3 }, 0)), P(0, 0), P(1, 1));
-
- // Transfer curve.
- var geo = new StreamGeometry();
- using (var g = geo.Open())
- {
- g.BeginFigure(P(0, Math.Clamp(_f(0), 0, 1)), false);
- for (int i = 1; i <= 64; i++) { double xn = i / 64.0; g.LineTo(P(xn, Math.Clamp(_f(xn), 0, 1))); }
- g.EndFigure(false);
- }
- ctx.DrawGeometry(null, new Pen(Brass, 1.8, lineJoin: PenLineJoin.Round), geo);
-
- // Recent-note dots.
- foreach (var d in _dots)
- {
- if (d.x <= 0 && d.y <= 0) continue; // empty slot
- ctx.DrawEllipse(Teal, null, P(d.x, d.y), 2, 2);
- }
- // Last note — a glowing dot.
- if (_last is { } l && (l.x > 0 || l.y > 0))
- {
- var p = P(l.x, l.y);
- ctx.DrawEllipse(NotaPalette.Wash(NotaPalette.AccentBright, 0x47), null, p, 7, 7);
- ctx.DrawEllipse(Bright, new Pen(Ink, 2), p, 4.5, 4.5);
- }
- }
-}
diff --git a/src/managed/Nota.App/Controls/VelocityHistoryViz.cs b/src/managed/Nota.App/Controls/VelocityHistoryViz.cs
new file mode 100644
index 00000000..a686cd2c
--- /dev/null
+++ b/src/managed/Nota.App/Controls/VelocityHistoryViz.cs
@@ -0,0 +1,101 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Velocity LAST 12 NOTES (almanac mockup 1a): one column per note, oldest left. The
+// outline is the velocity that came in, the fill the velocity that went out — the newest in
+// Brass Light, the rest in Brass Dim. Columns ease to their new heights as notes shift left,
+// so a stream of notes scrolls rather than flickers. A bypassed device greys the fills.
+
+using System;
+using System.Collections.Generic;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Media;
+
+namespace Nota.App;
+
+internal sealed class VelocityHistoryViz : Control
+{
+ private static readonly IBrush Outline = NotaPalette.BorderStrong;
+ private static readonly IBrush Fill = NotaPalette.AccentDim;
+ private static readonly IBrush FillNew = NotaPalette.AccentBright;
+ private static readonly IBrush FillOff = NotaPalette.BorderStrong;
+
+ public const int Slots = 12;
+ private const double Gap = 2;
+
+ private readonly double[] _in = new double[Slots], _out = new double[Slots];
+ private readonly double[] _tIn = new double[Slots], _tOut = new double[Slots];
+ private int _filled;
+ private long _count = -1;
+ private bool _bypassed;
+
+ public VelocityHistoryViz() { Height = 30; }
+
+ /// <summary>The recent (in, out) velocities 0..1, oldest first (at most 12), and the
+ /// running note count (a rise shifts the columns left before they ease in).</summary>
+ public void Set(IReadOnlyList<(double In, double Out)> notes, long count, bool bypassed)
+ {
+ int n = Math.Min(Slots, notes.Count);
+ // A new note: shift the shown columns left so the newcomer grows from nothing.
+ if (_count >= 0 && count > _count)
+ {
+ int shift = (int)Math.Min(Slots, count - _count);
+ for (int i = 0; i < Slots; i++)
+ {
+ int from = i + shift;
+ _in[i] = from < Slots ? _in[from] : 0;
+ _out[i] = from < Slots ? _out[from] : 0;
+ }
+ }
+ _count = count;
+ for (int i = 0; i < Slots; i++)
+ {
+ int k = i - (Slots - n);
+ _tIn[i] = k >= 0 ? notes[k].In : 0;
+ _tOut[i] = k >= 0 ? notes[k].Out : 0;
+ }
+ _filled = n;
+ const double ease = 0.35;
+ for (int i = 0; i < Slots; i++)
+ {
+ _in[i] += (_tIn[i] - _in[i]) * ease;
+ _out[i] += (_tOut[i] - _out[i]) * ease;
+ }
+ _bypassed = bypassed;
+ InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ double cw = (w - Gap * (Slots - 1)) / Slots;
+ var pen = new Pen(Outline, 1);
+ for (int i = 0; i < Slots; i++)
+ {
+ if (i < Slots - _filled && _in[i] < 0.004 && _out[i] < 0.004) continue;
+ double x = i * (cw + Gap);
+ double hi = Math.Round(_in[i] * h), ho = Math.Round(_out[i] * h);
+ if (hi >= 1)
+ {
+ // Outline without a bottom edge: left, top, right.
+ var g = new StreamGeometry();
+ using (var c = g.Open())
+ {
+ c.BeginFigure(new Point(x + 0.5, h), false);
+ c.LineTo(new Point(x + 0.5, h - hi + 0.5));
+ c.LineTo(new Point(x + cw - 0.5, h - hi + 0.5));
+ c.LineTo(new Point(x + cw - 0.5, h));
+ c.EndFigure(false);
+ }
+ ctx.DrawGeometry(null, pen, g);
+ }
+ if (ho >= 1)
+ {
+ var fill = _bypassed ? FillOff : i == Slots - 1 ? FillNew : Fill;
+ ctx.DrawRectangle(fill, null, new RoundedRect(new Rect(x + 2, h - ho, Math.Max(1, cw - 4), ho), 1, 1, 0, 0));
+ }
+ }
+ }
+}
diff --git a/src/managed/Nota.App/Controls/VelocityTransferViz.cs b/src/managed/Nota.App/Controls/VelocityTransferViz.cs
new file mode 100644
index 00000000..4833ac05
--- /dev/null
+++ b/src/managed/Nota.App/Controls/VelocityTransferViz.cs
@@ -0,0 +1,178 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Velocity TRANSFER plot (almanac mockups 1a / 1b): input velocity across, output up.
+// In a sunken well: the Out range as two dashed lines, the band Random can spread a note over
+// (a brass wash around the curve, clipped to the range), the transfer curve in brass and the
+// last 12 notes as dots — older ones fainter, the newest a Brass Light dot with a halo. The
+// full view adds the centre cross and the dashed identity diagonal.
+//
+// Motion: the curve and band glide to a new setting (a mode switch or a preset morphs rather
+// than jumps), and each new note pops in — the dot grows with a little overshoot while a ring
+// expands and fades. A bypassed device greys the curve and dots. The model is handed in by
+// the card (VelocityModel), which mirrors MidiVelocity.h, so the picture is what it plays.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Media;
+
+namespace Nota.App;
+
+internal sealed class VelocityTransferViz : Control
+{
+ private static readonly IBrush Well = NotaPalette.BgSunken;
+ private static readonly IBrush WellEdge = NotaPalette.GraphBorder;
+ private static readonly IBrush Cross = NotaPalette.GridBeat;
+ private static readonly IBrush Limit = NotaPalette.BorderStrong;
+ private static readonly IBrush Diag = NotaPalette.BorderDefault;
+ private static readonly IBrush Band = NotaPalette.Wash(NotaPalette.Accent, 0x1F);
+ private static readonly IBrush Curve = NotaPalette.Accent;
+ private static readonly IBrush CurveOff = NotaPalette.BorderStrong;
+ private static readonly IBrush Latest = NotaPalette.AccentBright;
+ private static readonly IBrush Halo = NotaPalette.Wash(NotaPalette.AccentBright, 0x40);
+
+ private const int N = 41; // curve samples across the input
+ private const double PopMs = 220, RingMs = 650;
+
+ /// <summary>The full (L) view: centre cross + identity diagonal, bigger dots with a halo.</summary>
+ public bool Full { get; init; }
+
+ // Shown (animated) and target shapes, output 0..1 per input sample.
+ private readonly double[] _curve = new double[N], _top = new double[N], _bot = new double[N];
+ private readonly double[] _tCurve = new double[N], _tTop = new double[N], _tBot = new double[N];
+ private double _lo, _hi = 1, _tLo, _tHi = 1;
+ private bool _primed, _bypassed;
+ private readonly List<(double In, double Out)> _dots = new();
+ private long _count = -1;
+ private long _popAt; // Stopwatch timestamp of the newest note's arrival (0 = none animating)
+
+ public VelocityTransferViz() { MinHeight = 40; ClipToBounds = true; }
+
+ /// <summary>Hand in the model. <paramref name="shape"/> maps input 0..1 to the output
+ /// before Random (already in the Out range); <paramref name="spread"/> is Random's
+ /// (down, up) offset, 0..1 units; <paramref name="dots"/> are the recent (in, out) notes,
+ /// oldest first; <paramref name="count"/> — notes shaped so far (a rise pops the newest).</summary>
+ public void Set(Func<double, double> shape, double lo, double hi, (double Down, double Up) spread,
+ IReadOnlyList<(double In, double Out)> dots, long count, bool bypassed)
+ {
+ for (int i = 0; i < N; i++)
+ {
+ double y = shape(i / (N - 1.0));
+ _tCurve[i] = y;
+ _tTop[i] = Math.Min(hi, y + spread.Up);
+ _tBot[i] = Math.Max(lo, y - spread.Down);
+ }
+ _tLo = lo; _tHi = hi;
+ if (!_primed)
+ {
+ Array.Copy(_tCurve, _curve, N); Array.Copy(_tTop, _top, N); Array.Copy(_tBot, _bot, N);
+ _lo = lo; _hi = hi; _primed = true;
+ }
+ else
+ {
+ // Glide ~40 % of the way per tick (60 Hz): settles in about a tenth of a second.
+ const double k = 0.4;
+ for (int i = 0; i < N; i++)
+ {
+ _curve[i] += (_tCurve[i] - _curve[i]) * k;
+ _top[i] += (_tTop[i] - _top[i]) * k;
+ _bot[i] += (_tBot[i] - _bot[i]) * k;
+ }
+ _lo += (_tLo - _lo) * k; _hi += (_tHi - _hi) * k;
+ }
+
+ _dots.Clear();
+ foreach (var d in dots) _dots.Add(d);
+ if (_count >= 0 && count > _count) _popAt = Stopwatch.GetTimestamp();
+ _count = count;
+ if (_popAt != 0 && Stopwatch.GetElapsedTime(_popAt).TotalMilliseconds > RingMs) _popAt = 0;
+ _bypassed = bypassed;
+ InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 2 || h <= 2) return;
+ var well = new Rect(0, 0, w, h);
+ ctx.DrawRectangle(Well, new Pen(WellEdge, 1), new RoundedRect(well.Deflate(0.5), NotaRadius.ControlValue));
+ using var clip = ctx.PushClip(new RoundedRect(well.Deflate(1), NotaRadius.ControlValue));
+ double iw = w - 2, ih = h - 2;
+ Point P(double xn, double yn) => new(1 + xn * iw, 1 + (1 - Math.Clamp(yn, 0, 1)) * ih);
+
+ if (Full)
+ {
+ var cross = new Pen(Cross, 1);
+ ctx.DrawLine(cross, new Point(Math.Round(w / 2) + 0.5, 0), new Point(Math.Round(w / 2) + 0.5, h));
+ ctx.DrawLine(cross, new Point(0, Math.Round(h / 2) + 0.5), new Point(w, Math.Round(h / 2) + 0.5));
+ }
+ var dash = new Pen(Limit, 1, dashStyle: new DashStyle(new double[] { 3, 3 }, 0));
+ double yHi = Math.Round(P(0, _hi).Y) + 0.5, yLo = Math.Round(P(0, _lo).Y) + 0.5;
+ ctx.DrawLine(dash, new Point(0, yHi), new Point(w, yHi));
+ ctx.DrawLine(dash, new Point(0, yLo), new Point(w, yLo));
+
+ // Random's band.
+ bool any = false;
+ for (int i = 0; i < N && !any; i++) any = _top[i] - _bot[i] > 0.002;
+ if (any)
+ {
+ var band = new StreamGeometry();
+ using (var g = band.Open())
+ {
+ g.BeginFigure(P(0, _top[0]), true);
+ for (int i = 1; i < N; i++) g.LineTo(P(i / (N - 1.0), _top[i]));
+ for (int i = N - 1; i >= 0; i--) g.LineTo(P(i / (N - 1.0), _bot[i]));
+ g.EndFigure(true);
+ }
+ ctx.DrawGeometry(Band, null, band);
+ }
+
+ if (Full) ctx.DrawLine(new Pen(Diag, 1, dashStyle: new DashStyle(new double[] { 3, 3 }, 0)), P(0, 0), P(1, 1));
+
+ var geo = new StreamGeometry();
+ using (var g = geo.Open())
+ {
+ g.BeginFigure(P(0, _curve[0]), false);
+ for (int i = 1; i < N; i++) g.LineTo(P(i / (N - 1.0), _curve[i]));
+ g.EndFigure(false);
+ }
+ ctx.DrawGeometry(null, new Pen(_bypassed ? CurveOff : Curve, 2, lineJoin: PenLineJoin.Round, lineCap: PenLineCap.Round), geo);
+
+ // Notes: oldest faint → newest bright; the newest pops in.
+ int n = _dots.Count;
+ double popT = _popAt == 0 ? 1 : Stopwatch.GetElapsedTime(_popAt).TotalMilliseconds;
+ for (int i = 0; i < n; i++)
+ {
+ var (xi, yo) = _dots[i];
+ var p = P(xi, yo);
+ bool latest = i == n - 1;
+ if (!latest)
+ {
+ double a = 0.25 + 0.5 * (i + 12 - n) / 12.0;
+ var ink = _bypassed ? CurveOff : NotaPalette.Wash(NotaPalette.Accent, (byte)Math.Round(a * 255));
+ double r = Full ? 2.5 : 2;
+ ctx.DrawEllipse(ink, null, p, r, r);
+ continue;
+ }
+ double r0 = Full ? 4.5 : 3.5;
+ double grow = _popAt == 0 ? 1 : EaseOutBack(Math.Clamp(popT / PopMs, 0, 1));
+ if (_popAt != 0 && !_bypassed)
+ {
+ double u = Math.Clamp(popT / RingMs, 0, 1);
+ double rr = r0 + 2 + u * (Full ? 12 : 8);
+ ctx.DrawEllipse(null, new Pen(NotaPalette.Wash(NotaPalette.AccentBright, (byte)Math.Round((1 - u) * 0.6 * 255)), 1.5), p, rr, rr);
+ }
+ if (Full && !_bypassed) ctx.DrawEllipse(Halo, null, p, (r0 + 3) * grow, (r0 + 3) * grow);
+ ctx.DrawEllipse(_bypassed ? CurveOff : Latest, null, p, r0 * grow, r0 * grow);
+ }
+ }
+
+ private static double EaseOutBack(double t)
+ {
+ const double c1 = 1.70158, c3 = c1 + 1;
+ return 1 + c3 * Math.Pow(t - 1, 3) + c1 * Math.Pow(t - 1, 2);
+ }
+}
diff --git a/src/managed/Nota.App/DeviceCards/IInstrumentCard.cs b/src/managed/Nota.App/DeviceCards/IInstrumentCard.cs
index 8239bbe6..4235d7a0 100644
--- a/src/managed/Nota.App/DeviceCards/IInstrumentCard.cs
+++ b/src/managed/Nota.App/DeviceCards/IInstrumentCard.cs
@@ -28,4 +28,13 @@ internal interface IInstrumentCard
/// <summary>Voice readout for the shell header (e.g. "3/5"), or null for the default
/// "active/16". Called on the live-refresh tick. Only used when BodyOnly.</summary>
string? VoiceLabel(Nota.Application.IAudioEngine engine, int trackId, int active) => null;
+
+ /// <summary>Card width for this track's instrument — a card with S / L sizes (the
+ /// instrument's "view" param, see InstrumentView) returns 260 for S. A width under 300
+ /// makes the shell compact (no type badge, a narrower preset picker). Only used when BodyOnly.</summary>
+ double WidthFor(Nota.Application.IAudioEngine engine, int trackId) => CardWidth;
+
+ /// <summary>Extra controls for the shell header, left of the bypass (e.g. the S / L
+ /// toggle). Only used when BodyOnly.</summary>
+ Control? HeaderAccessory(DeviceCardContext ctx) => null;
}
diff --git a/src/managed/Nota.App/DeviceCards/Instruments/SynthInstrumentCard.cs b/src/managed/Nota.App/DeviceCards/Instruments/SynthInstrumentCard.cs
index 3d2f8774..7304fb63 100644
--- a/src/managed/Nota.App/DeviceCards/Instruments/SynthInstrumentCard.cs
+++ b/src/managed/Nota.App/DeviceCards/Instruments/SynthInstrumentCard.cs
@@ -12,6 +12,14 @@
// A 186px rail stays put on every tab — voice mode, volume, pan, glide, unison spread,
// velocity tracking and the track's meter — over a status strip that reads the patch back
// in words. Brass is the parameter itself; teal is modulation (detune, env → cutoff).
+//
+// Two sizes share every value; the S / L toggle in the shell header flips the card (the
+// choice is the synth's "view" param — see InstrumentView — so it persists with the
+// project; a new Synth opens as S):
+// • L 700 × 260 — the tabs + rail above.
+// • S 260 × 260 — the filter curve (drag for cutoff / reso, the wave named on it) over
+// Cutoff · Reso · Attack · Release; voices, glide and output fold into the status line.
+// The header keeps the full preset picker — presets still set what S can't show.
using System;
using System.Collections.Generic;
@@ -30,7 +38,20 @@ internal sealed class SynthInstrumentCard : IInstrumentCard
public bool BodyOnly => true;
public string Subtitle => "SUBTRACTIVE";
- private const double RailW = 186, TabH = 20, StatusH = 18, RowH = 60;
+ public double WidthFor(IAudioEngine engine, int trackId) => InstrumentView.IsMini(engine, trackId) ? 260 : 700;
+
+ // L: MIDI Learn · S/L. S: S/L only (the shell keeps the same, narrower, preset picker).
+ public Control? HeaderAccessory(DeviceCardContext ctx)
+ {
+ var e = ctx.Engine; int t = ctx.TrackId;
+ if (InstrumentView.Index(e, t) < 0) return null;
+ var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center };
+ if (!InstrumentView.IsMini(e, t)) row.Children.Add(MidiCardHeader.LearnButton(ctx));
+ row.Children.Add(MidiCardHeader.SizeToggle(ctx, () => InstrumentView.IsMini(e, t), m => InstrumentView.SetMini(e, t, m)));
+ return row;
+ }
+
+ private const double RailW = 186, TabH = 20, StatusH = 18, RowH = 60, MiniRowH = 53;
private static readonly string[] WaveNames = { "Saw", "Square", "Triangle", "Sine" };
private static readonly string[] FilterNames = { "Off", "LP", "HP", "BP" };
@@ -72,12 +93,13 @@ internal sealed class SynthInstrumentCard : IInstrumentCard
void SetP(string id, float v) { if (I(id) is var i and >= 0) engine.PluginParamSet(track, -1, i, Math.Clamp(v, 0f, 1f)); }
int Sel(string id, int n) => Math.Clamp((int)Math.Round(G(id) * (n - 1)), 0, n - 1);
+ bool mini = InstrumentView.IsMini(engine, track);
var readouts = new List<Action>(); // everything that re-reads a param
int tab = 0; // the open tab: 0 Osc · 1 Env · 2 Filter
var bodies = new (Control Graph, Control Row)[TabNames.Length];
var osc = new SynthViz(SynthViz.K.Osc, engine, track, idx);
var env = new SynthViz(SynthViz.K.Adsr, engine, track, idx);
- var flt = new SynthViz(SynthViz.K.Filter, engine, track, idx);
+ var flt = new SynthViz(SynthViz.K.Filter, engine, track, idx) { Mini = mini };
var status = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
var meta = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center };
meta.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
@@ -133,6 +155,8 @@ internal sealed class SynthInstrumentCard : IInstrumentCard
};
}
+ if (mini) return BuildMini(ctx, flt, Knob, readouts, Refresh, () => Sel("filtype", 4) == 0, status, meta);
+
// ---- Osc tab ----------------------------------------------------------
var pwKnobCell = Knob("pulsewidth", "Pulse W", v => NotaNum.Pct(0.05 + v * 0.90));
// Pulse width only shapes the square — dim it (never hide it) on the other shapes.
@@ -330,7 +354,9 @@ internal sealed class SynthInstrumentCard : IInstrumentCard
rail.Width = RailW;
// ---- status strip -----------------------------------------------------
- string Summary() => tab switch
+ string Summary() => mini
+ ? $"{VoiceNames[Sel("voicemode", 3)]} · glide {Glide(G("glide"))}"
+ : tab switch
{
0 => $"{WaveNames[Sel("wave", 4)]} · unison {UnisonCounts[Sel("unison", 4)]} · detune {Cents(G("detune"))}"
+ (Sel("wave", 4) == 1 ? $" · pulse {NotaNum.Pct(0.05 + G("pulsewidth") * 0.90)}" : ""),
@@ -341,23 +367,13 @@ internal sealed class SynthInstrumentCard : IInstrumentCard
};
string Meta()
{
+ if (mini) return $"out {Db(G("gain"))}";
int uni = UnisonCounts[Sel("unison", 4)];
string mode = VoiceNames[Sel("voicemode", 3)].ToUpperInvariant();
string oct = Octaves(G("octave"));
return $"{mode} · UNISON {uni} · OCT {oct} · {Db(G("gain"))}";
}
- var statusBar = new Grid
- {
- Height = StatusH, ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 10,
- Background = NotaPalette.SurfaceAbyss,
- };
- 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,
- };
- statusBar.Children.Add(status);
- Grid.SetColumn(meta, 1); statusBar.Children.Add(meta);
+ var statusHost = StatusStrip(status, meta);
// ---- assembly ---------------------------------------------------------
var body = new Grid
@@ -378,6 +394,70 @@ internal sealed class SynthInstrumentCard : IInstrumentCard
return root;
}
+ // ---- S: the mini card -------------------------------------------------------
+ // One island: the filter window fills it, the four main knobs sit under it, spaced
+ // evenly across the 260 card; the status strip carries voices / glide / output.
+ private static Control BuildMini(DeviceCardContext ctx, SynthViz flt,
+ Func<string, string, Func<float, string>, double, double, IBrush?, Control> knob,
+ List<Action> readouts, Action refresh, Func<bool> filterOff, TextBlock status, TextBlock meta)
+ {
+ var cells = new[]
+ {
+ knob("cutoff", "Cutoff", KHz, 34, 52, null),
+ knob("resonance", "Reso", v => v.ToString("0.00", NotaNum.Culture), 34, 52, null),
+ knob("attack", "Attack", v => Secs(v, 0.001, 2.0), 34, 52, null),
+ knob("release", "Release", v => Secs(v, 0.002, 3.0), 34, 52, null),
+ };
+ var knobRow = new Grid { Height = MiniRowH, ColumnDefinitions = new ColumnDefinitions("*,*,*,*") };
+ for (int i = 0; i < cells.Length; i++)
+ {
+ cells[i].HorizontalAlignment = HorizontalAlignment.Center;
+ cells[i].VerticalAlignment = VerticalAlignment.Top;
+ Grid.SetColumn(cells[i], i); knobRow.Children.Add(cells[i]);
+ }
+ // Off bypasses the filter — its two knobs go inactive but stay editable.
+ var cutKnob = FindKnob(cells[0]); var resoKnob = FindKnob(cells[1]);
+ readouts.Add(() =>
+ {
+ bool off = filterOff();
+ if (cutKnob is not null) cutKnob.IsDim = off;
+ if (resoKnob is not null) resoKnob.IsDim = off;
+ });
+
+ var inner = new Grid { RowDefinitions = new RowDefinitions("*,Auto"), RowSpacing = 4, Margin = new Thickness(6, 6, 6, 0) };
+ inner.Children.Add(flt);
+ Grid.SetRow(knobRow, 1); inner.Children.Add(knobRow);
+ var island = SectionBox(inner);
+ island.Margin = new Thickness(NotaSpace.DeviceGap);
+
+ var statusHost = StatusStrip(status, meta);
+ DockPanel.SetDock(statusHost, Dock.Bottom);
+ var root = new DockPanel
+ {
+ LastChildFill = true, Background = NotaPalette.Gutter,
+ Children = { statusHost, island },
+ };
+ refresh();
+ return root;
+ }
+
+ // The 18px strip under the card: the patch in words on the left, a mono readout right.
+ private static Border StatusStrip(TextBlock status, TextBlock meta)
+ {
+ var bar = new Grid
+ {
+ Height = StatusH, ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 10,
+ Background = NotaPalette.SurfaceAbyss,
+ };
+ bar.Children.Add(status);
+ Grid.SetColumn(meta, 1); bar.Children.Add(meta);
+ return new Border
+ {
+ Height = StatusH, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 1, 0, 0),
+ Background = NotaPalette.SurfaceAbyss, Padding = new Thickness(8, 0), Child = bar,
+ };
+ }
+
public string? VoiceLabel(IAudioEngine engine, int trackId, int active)
{
int i = -1, pc = engine.PluginParamCount(trackId, -1);
diff --git a/src/managed/Nota.App/DeviceCards/Midi/MidiCardHeader.cs b/src/managed/Nota.App/DeviceCards/Midi/MidiCardHeader.cs
index 8fb4620e..d1c075a1 100644
--- a/src/managed/Nota.App/DeviceCards/Midi/MidiCardHeader.cs
+++ b/src/managed/Nota.App/DeviceCards/Midi/MidiCardHeader.cs
@@ -1,8 +1,8 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Shell-header pieces shared by the MIDI-effect cards that come in two sizes (Nota Arp,
-// Nota Chord): the MIDI Learn button that mirrors the transport's Learn toggle, and the
+// Shell-header pieces shared by the cards that come in two sizes (Nota Arp, Nota Chord,
+// Nota Synth …): the MIDI Learn button that mirrors the transport's Learn toggle, and the
// S / L size toggle bound to the device's "View" param (0 = L, 1 = S).
using System;
@@ -41,10 +41,14 @@ internal static class MidiCardHeader
}
public static Control SizeToggle(DeviceCardContext ctx, int index, int viewParam, Func<bool> isMini)
+ => SizeToggle(ctx, isMini, mini => ctx.Engine.MidiEffectSetParam(ctx.TrackId, index, viewParam, mini ? 1f : 0f));
+
+ /// <summary>The S / L toggle over any size store — a MIDI effect's View param, or an
+ /// instrument's "view" param (InstrumentView). Flipping it rebuilds the chain.</summary>
+ public static Control SizeToggle(DeviceCardContext ctx, Func<bool> isMini, Action<bool> setMini)
{
- var e = ctx.Engine; int t = ctx.TrackId;
var size = DeviceCardKit.Segments(new[] { "S", "L" }, () => isMini() ? 0 : 1,
- i => { e.MidiEffectSetParam(t, index, viewParam, i == 0 ? 1f : 0f); ctx.RequestRebuild(); }, out _, padX: 0, minSegWidth: 16, fontSize: 8);
+ i => { setMini(i == 0); ctx.RequestRebuild(); }, out _, padX: 0, minSegWidth: 16, fontSize: 8);
ToolTip.SetTip(size, "Card size: S (mini) / L (full)");
return size;
}
diff --git a/src/managed/Nota.App/DeviceCards/Midi/VelocityMidiBody.cs b/src/managed/Nota.App/DeviceCards/Midi/VelocityMidiBody.cs
index 4500abcf..4ff56d10 100644
--- a/src/managed/Nota.App/DeviceCards/Midi/VelocityMidiBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Midi/VelocityMidiBody.cs
@@ -1,191 +1,500 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Detail · Devices — the Nota Velocity editor (MIDI effect kind 4), mockup 3b (700×260 on the
-// shared shell): a LIVE strip (shape Mode — Curve / Compand / Fixed — with its drive/fixed +
-// random controls) over a body of the TRANSFER curve (input→output velocity, the last notes
-// plotted on it) beside a right rail (Out Range, Random on + direction, a Last-12-notes
-// histogram). The transfer maths mirror MidiVelocity.h so picture == sound.
+// Detail · Devices — the Nota Velocity editor (MIDI effect kind 4), almanac mockups 1a / 1b.
+// Two sizes share every value; the S / L toggle in the shell header flips the card (the
+// choice is the device's "View" param, so it persists with the project):
+// • L 700 × 260 — MODE (Curve / Compand / Fixed as a list, then Drive — or the Fixed value —
+// with its slider and what it does) | TRANSFER (input across, output up: the curve, the
+// band Random can spread a note over, the Out range as dashed lines, the last 12 notes as
+// dots) | OUT RANGE (a two-handle range, the Random switch + amount + Both / Up / Down, a
+// LAST 12 NOTES histogram: outline in, fill out) — over a status line.
+// • S 260 × 260 — the mode chip over the TRANSFER window and four knobs (Drive or Value ·
+// Random · Low · High); the footer's "random both" steps Both → Up → Down → off.
+// Dots and bars are the real notes the device shaped (telemetry), not a demo. The maths is
+// VelocityModel, a mirror of MidiVelocity.h, so picture == sound.
using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
-using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
+using Nota.Application;
namespace Nota.App;
+/// <summary>Nota Velocity's transfer model in musical units — mirrors MidiVelocity.h.</summary>
+internal static class VelocityModel
+{
+ internal const int PDrive = 0, PFixed = 1, POutLo = 2, PRandom = 3, PMode = 4, POutHi = 5, PRandomDir = 6, PRandomOn = 7, PView = 8;
+ internal static readonly string[] Modes = { "Curve", "Compand", "Fixed" };
+ internal static readonly string[] ModeHints = { "x^1/d", "S", "=" };
+ internal static readonly string[] Dirs = { "Both", "Up", "Down" };
+ internal const double DriveMin = 0.25, DriveMax = 4.0, RandomSpan = 64;
+
+ internal static int Mode(Func<int, float> g) => Math.Clamp((int)Math.Round(g(PMode)), 0, 2);
+ internal static int Dir(Func<int, float> g) => Math.Clamp((int)Math.Round(g(PRandomDir)), 0, 2);
+ internal static bool RandomOn(Func<int, float> g) => g(PRandomOn) >= 0.5f;
+ internal static double Drive(Func<int, float> g) => Math.Clamp(g(PDrive), 0.05, DriveMax);
+
+ /// <summary>Drive's 0..1 control position: drive = 4^(2f − 1), so 1.00 sits in the middle.</summary>
+ internal static double DriveNorm(double d) => Math.Clamp((Math.Log(Math.Max(DriveMin, d), 4) + 1) / 2, 0, 1);
+ internal static double DriveFromNorm(double n) => Math.Round(Math.Pow(4, Math.Clamp(n, 0, 1) * 2 - 1), 2);
+
+ /// <summary>The Fixed value / Out range ends as MIDI velocities 1..127.</summary>
+ internal static int Vel(float norm) => Math.Clamp((int)Math.Round(norm * 127), 1, 127);
+ internal static int Fixed(Func<int, float> g) => Vel(g(PFixed));
+ internal static (int Lo, int Hi) Range(Func<int, float> g)
+ {
+ int lo = Vel(g(POutLo)), hi = Vel(g(POutHi));
+ return lo <= hi ? (lo, hi) : (hi, lo);
+ }
+ /// <summary>Random as ± velocity (0..64).</summary>
+ internal static int RandomAmt(Func<int, float> g) => (int)Math.Round(Math.Clamp(g(PRandom), 0, 1) * RandomSpan);
+
+ /// <summary>The transfer shape 0..1 → 0..1 (MidiVelocity::transfer).</summary>
+ internal static double Shape(double n, int mode, double drive, double fixedN)
+ {
+ n = Math.Clamp(n, 0, 1);
+ if (mode == 2) return fixedN;
+ if (mode == 1)
+ {
+ double c = 2 * n - 1;
+ return Math.Clamp(0.5 + Math.Sign(c) * Math.Pow(Math.Abs(c), 1 / drive) * 0.5, 0, 1);
+ }
+ return Math.Pow(n, 1 / drive);
+ }
+
+ /// <summary>Output (0..1) before Random for an input 0..1: the shape, into the Out range.</summary>
+ internal static double Base(Func<int, float> g, double n)
+ {
+ var (lo, hi) = RangeN(g);
+ return lo + Shape(n, Mode(g), Drive(g), Math.Clamp(g(PFixed), 0, 1)) * (hi - lo);
+ }
+ internal static (double Lo, double Hi) RangeN(Func<int, float> g)
+ {
+ double lo = Math.Clamp(g(POutLo), 0, 1), hi = Math.Clamp(g(POutHi), 0, 1);
+ if (lo > hi) (lo, hi) = (hi, lo);
+ return (Math.Max(lo, 1 / 127.0), Math.Max(hi, 1 / 127.0));
+ }
+ /// <summary>Random's (down, up) reach in 0..1 units — (0, 0) while the switch is off.</summary>
+ internal static (double Down, double Up) Spread(Func<int, float> g)
+ {
+ if (!RandomOn(g)) return (0, 0);
+ double r = Math.Clamp(g(PRandom), 0, 1) * RandomSpan / 127.0;
+ return Dir(g) switch { 1 => (0, r), 2 => (r, 0), _ => (r, r) };
+ }
+
+ internal static string DriveText(Func<int, float> g) => Mode(g) == 2 ? Fixed(g).ToString() : $"{Drive(g):0.00}";
+ internal static string RandomText(Func<int, float> g)
+ {
+ int r = RandomAmt(g);
+ return Dir(g) switch { 1 => $"+{r}", 2 => $"−{r}", _ => $"±{r}" };
+ }
+ internal static string DriveHint(Func<int, float> g)
+ {
+ int mode = Mode(g); double d = Drive(g);
+ if (mode == 2) return "every note at this velocity";
+ if (Math.Abs(d - 1) < 0.005) return "linear";
+ return mode == 0 ? (d > 1 ? "soft notes louder" : "soft notes quieter")
+ : (d > 1 ? "stretched to the edges" : "squeezed to the middle");
+ }
+}
+
internal sealed class VelocityMidiBody : IMidiDeviceBody
{
- private const int PDrive = 0, PFixed = 1, POutLo = 2, PRandom = 3, PMode = 4, POutHi = 5, PRandomDir = 6;
- private static readonly string[] Modes = { "Curve", "Compand", "Fixed" };
- private static readonly string[] Dirs = { "Both", "Up", "Down" };
+ private const int PDrive = VelocityModel.PDrive, PFixed = VelocityModel.PFixed, POutLo = VelocityModel.POutLo,
+ PRandom = VelocityModel.PRandom, PMode = VelocityModel.PMode, POutHi = VelocityModel.POutHi,
+ PRandomDir = VelocityModel.PRandomDir, PRandomOn = VelocityModel.PRandomOn;
+ internal const int PView = VelocityModel.PView;
+ private static readonly string[] Modes = VelocityModel.Modes;
+ private static readonly string[] Dirs = VelocityModel.Dirs;
- private static readonly IBrush HdrBg = NotaPalette.SurfaceCard;
- private static readonly IBrush RailBg = NotaPalette.SurfaceInset;
+ private static readonly IBrush Ground = NotaPalette.SurfaceInset;
+ private static readonly IBrush Island = NotaPalette.SurfaceCard;
private static readonly IBrush Bd = NotaPalette.BorderDefault;
- private static readonly IBrush Inset = NotaPalette.BgSunken;
- private static readonly IBrush Amber = NotaPalette.Accent;
- private static readonly IBrush AmberLit = NotaPalette.AccentBright;
- private static readonly IBrush AmberDim = NotaPalette.Wash(NotaPalette.Accent, 0x73);
- private static readonly IBrush Teal = NotaPalette.Teal;
+ private static readonly IBrush Rule = NotaPalette.GraphBorder;
+ private static readonly IBrush Well = NotaPalette.BgSunken;
+ private static readonly IBrush BrassLit = NotaPalette.AccentBright;
private static readonly IBrush Txt = NotaPalette.TextPrimary;
- private static readonly IBrush Muted = NotaPalette.TextTertiary;
private static readonly IBrush Sub = NotaPalette.TextSecondary;
- private static readonly IBrush Ink = NotaPalette.TextOnAccent;
- private static readonly IBrush AmberSubtle = NotaPalette.Wash(NotaPalette.Accent, 0x28);
+ private static readonly IBrush Cap = NotaPalette.TextTertiary;
+ private static readonly IBrush Axis = NotaPalette.TextAxis;
+ private static readonly IBrush AxisLbl = NotaPalette.TextDisabled;
public double Width => 700;
public bool FullBleed => true;
+ private static bool HasLayout(IAudioEngine e, int track, int mi) => e.MidiEffectParamCount(track, mi) > PView;
+ private static bool IsMini(IAudioEngine e, int track, int mi) => HasLayout(e, track, mi) && e.MidiEffectGetParam(track, mi, PView) >= 0.5f;
+ public double WidthFor(IAudioEngine engine, int trackId, int index) => IsMini(engine, trackId, index) ? 260 : 700;
+
+ public Control? HeaderAccessory(DeviceCardContext ctx, int index)
+ {
+ var e = ctx.Engine; int t = ctx.TrackId;
+ if (!HasLayout(e, t, index)) return null;
+ var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center };
+ if (!IsMini(e, t, index))
+ {
+ var tag = Mono("", Cap, 8); tag.LetterSpacing = 0.6;
+ void Sync() => tag.Text = Modes[VelocityModel.Mode(p => e.MidiEffectGetParam(t, index, p))].ToUpperInvariant();
+ Sync();
+ ctx.AddDeviceRefresher(Sync);
+ ToolTip.SetTip(tag, "Velocity mode");
+ row.Children.Add(tag); row.Children.Add(MidiCardHeader.LearnButton(ctx));
+ }
+ row.Children.Add(MidiCardHeader.SizeToggle(ctx, index, PView, () => IsMini(e, t, index)));
+ return row;
+ }
+
+ // ---- small builders -------------------------------------------------------------------------
+ private static TextBlock Caps(string t, IBrush? c = null, double fs = 7) => new()
+ { Text = t, FontSize = fs, FontWeight = FontWeight.Bold, LetterSpacing = 0.8, Foreground = c ?? Cap, VerticalAlignment = VerticalAlignment.Center };
+ private static TextBlock Mono(string t, IBrush c, double fs = 8) => new()
+ { Text = t, FontSize = fs, FontFamily = NotaFonts.MonoFamily, Foreground = c, VerticalAlignment = VerticalAlignment.Center };
+ private static T WithDock<T>(T c, Dock d) where T : Control { DockPanel.SetDock(c, d); return c; }
+
+ // ---- body -------------------------------------------------------------------------------------
public Control Build(DeviceCardContext ctx, int index)
{
- var engine = ctx.Engine;
- int track = ctx.TrackId, mi = index;
+ var engine = ctx.Engine; int track = ctx.TrackId, mi = index;
+ if (!HasLayout(engine, track, mi)) return new TextBlock { Text = "Nota Velocity", Margin = new Thickness(8) };
float G(int p) => engine.MidiEffectGetParam(track, mi, p);
+ float Def(int p) => engine.MidiEffectParamDefault(track, mi, p);
void S(int p, double v) => engine.MidiEffectSetParam(track, mi, p, (float)v);
- int Gi(int p) => (int)Math.Round(G(p));
+ void Begin(int p) => engine.BeginAutomationWrite(track, AutomationTarget.MidiDeviceParam, mi, p, "");
+ void End(int p) => engine.EndAutomationWrite(track, AutomationTarget.MidiDeviceParam, mi, p, "");
+ void Set1(int p, double v) { Begin(p); S(p, v); End(p); }
+ void Learn(Control c, int p, string name) => MidiLearn.Bind(c, MidiTarget.MidiDeviceParam(track, mi, p), name);
+ bool Bypassed() => engine.MidiEffectBypassed(track, mi);
+ int Mode() => VelocityModel.Mode(G);
+ bool IsFixed() => Mode() == 2;
+ bool mini = IsMini(engine, track, mi);
var readouts = new List<Action>();
- double lastRnd = 0.2;
- static TextBlock Cap(string t, IBrush? c = null, double fs = 8) => new() { Text = t, FontSize = fs, FontWeight = FontWeight.Bold, Foreground = c ?? Muted, VerticalAlignment = VerticalAlignment.Center };
- static 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; }
void Refresh() { foreach (var r in readouts) r(); }
- // Transfer (mirrors MidiVelocity::transfer + the out-range remap).
- double Transfer(double n)
+ // ---- live notes from the device (oldest → newest) ------------------------------------------
+ var scope = new float[25];
+ var notes = new List<(double In, double Out)>(12);
+ long count = 0;
+ void Poll()
{
- int mode = Gi(PMode); double drive = Math.Clamp(G(PDrive), 0.05, 2), fixd = G(PFixed);
- double shaped = mode == 2 ? fixd
- : mode == 1 ? Math.Clamp(0.5 + Math.Sign(2 * n - 1) * Math.Pow(Math.Abs(2 * n - 1), 1 / drive) * 0.5, 0, 1)
- : Math.Pow(Math.Clamp(n, 0, 1), 1 / drive);
- double lo = G(POutLo), hi = G(POutHi); if (lo > hi) (lo, hi) = (hi, lo);
- return lo + shaped * (hi - lo);
+ int n = engine.MidiEffectScope(track, mi, scope);
+ count = n >= 25 ? (long)scope[24] : 0;
+ notes.Clear();
+ int have = (int)Math.Min(12, count);
+ for (int k = 12 - have; k < 12 && 2 * k + 1 < n; k++) notes.Add((scope[2 * k], scope[2 * k + 1]));
}
+ (int In, int Out)? Last() => notes.Count > 0 ? ((int)Math.Round(notes[^1].In * 127), (int)Math.Round(notes[^1].Out * 127)) : null;
+
+ // DRIVE / VALUE: one control whose target follows the mode.
+ int DriveParam() => IsFixed() ? PFixed : PDrive;
+ double DriveNorm() => IsFixed() ? (VelocityModel.Fixed(G) - 1) / 126.0 : VelocityModel.DriveNorm(VelocityModel.Drive(G));
+ void DriveSet(double n)
+ {
+ if (IsFixed()) S(PFixed, Math.Round(1 + Math.Clamp(n, 0, 1) * 126) / 127.0);
+ else S(PDrive, VelocityModel.DriveFromNorm(n));
+ }
+ string DriveLabel() => IsFixed() ? "VALUE" : "DRIVE";
+
+ // The Out range in whole velocities, keeping low below high.
+ void SetLo(double v) { var (_, hi) = VelocityModel.Range(G); S(POutLo, Math.Clamp(Math.Round(v), 1, hi - 1) / 127.0); }
+ void SetHi(double v) { var (lo, _) = VelocityModel.Range(G); S(POutHi, Math.Clamp(Math.Round(v), lo + 1, 127) / 127.0); }
+
+ Poll();
+ Control rootView = mini ? BuildMini() : BuildLarge();
+ ctx.AddDeviceRefresher(() => { Poll(); Refresh(); });
+ Refresh();
+ return rootView;
- // ---- generic controls ----
- Control MiniSlider(string label, int p, double min, double max, Func<double, string> fmt, double w)
+ // =========================================================================================
+ Control BuildLarge()
{
- var row = DeviceCardKit.SliderRow(label, () => (G(p) - min) / (max - min), n => { S(p, min + n * (max - min)); Refresh(); }, () => fmt(G(p)), out var sync,
- trackWidth: w, valueWidth: 26);
- MidiLearn.Bind(row, MidiTarget.MidiDeviceParam(track, mi, p), engine.MidiEffectParamName(track, mi, p));
- readouts.Add(sync);
- return row;
+ // ---- MODE ----
+ var list = new StackPanel { Margin = new Thickness(0, 3) };
+ for (int i = 0; i < Modes.Length; i++)
+ {
+ int m = i;
+ var bar = new Border { Width = 2, Margin = new Thickness(0, 3), HorizontalAlignment = HorizontalAlignment.Left };
+ var name = new TextBlock { Text = Modes[m], FontSize = 9, VerticalAlignment = VerticalAlignment.Center };
+ var hint = Mono(VelocityModel.ModeHints[m], Axis, 7); hint.HorizontalAlignment = HorizontalAlignment.Right;
+ var rowB = new Border { Height = 18, Cursor = new Cursor(StandardCursorType.Hand),
+ Child = new Panel { Children = { bar, new DockPanel { Margin = new Thickness(8, 0), Children = { WithDock(hint, Dock.Right), name } } } } };
+ bool hover = false;
+ void Paint()
+ {
+ bool on = Mode() == m;
+ rowB.Background = on ? NotaPalette.AccentSubtle : hover ? NotaPalette.GridBeat : Brushes.Transparent;
+ bar.Background = on ? NotaPalette.Accent : Brushes.Transparent;
+ name.Foreground = on ? Txt : Sub; name.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
+ }
+ rowB.PointerEntered += (_, _) => { hover = true; Paint(); };
+ rowB.PointerExited += (_, _) => { hover = false; Paint(); };
+ rowB.PointerPressed += (_, ev) =>
+ {
+ if (!ev.GetCurrentPoint(rowB).Properties.IsLeftButtonPressed) return;
+ Set1(PMode, m); Refresh(); ev.Handled = true;
+ };
+ ToolTip.SetTip(rowB, m switch
+ {
+ 0 => "Curve — bend the response: Drive above 1 lifts soft notes, below 1 pushes them down",
+ 1 => "Compand — the same around the middle: above 1 stretches to the edges, below 1 squeezes to the middle",
+ _ => "Fixed — every note comes out at one velocity",
+ });
+ Learn(rowB, PMode, "Mode");
+ readouts.Add(Paint);
+ list.Children.Add(rowB);
+ }
+
+ var dLabel = Caps("DRIVE");
+ var dValue = Mono("", BrassLit, 13); dValue.FontWeight = FontWeight.Medium; dValue.HorizontalAlignment = HorizontalAlignment.Right;
+ int dGesture = -1;
+ var dTrack = new SliderTrack { Height = 11, Reset = () => { int p = DriveParam(); Set1(p, Def(p)); Refresh(); } };
+ dTrack.Changed += n => { DriveSet(n); Refresh(); };
+ dTrack.GestureBegin += () => { dGesture = DriveParam(); Begin(dGesture); };
+ dTrack.GestureEnd += () => { if (dGesture >= 0) End(dGesture); dGesture = -1; };
+ ToolTip.SetTip(dTrack, "Drag up / down, Shift for fine, double-click resets");
+ Learn(dTrack, PDrive, "Drive");
+ var dHint = new TextBlock { FontSize = 7, Foreground = Cap, TextTrimming = TextTrimming.CharacterEllipsis };
+ readouts.Add(() =>
+ {
+ dLabel.Text = DriveLabel(); dValue.Text = VelocityModel.DriveText(G); dHint.Text = VelocityModel.DriveHint(G);
+ if (!dTrack.Dragging) dTrack.Norm = DriveNorm();
+ });
+ var driveBox = new Border
+ {
+ BorderBrush = Rule, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(8, 6),
+ Child = new StackPanel { Spacing = 3, Children = { new DockPanel { Children = { WithDock(dValue, Dock.Right), dLabel } }, dTrack, dHint } },
+ };
+ var modeIsland = IslandBox(IslandHead(Caps("MODE"), null), new DockPanel { Children = { WithDock(driveBox, Dock.Bottom), WithDock(list, Dock.Top) } }, 120);
+
+ // ---- TRANSFER ----
+ var viz = new VelocityTransferViz { Full = true };
+ ToolTip.SetTip(viz, "Input velocity across, output up. Dashed — the Out range; the band — where Random can put a note; dots — the last notes played");
+ var plotInfo = Mono("", BrassLit, 7);
+ readouts.Add(() =>
+ {
+ viz.Set(n => VelocityModel.Base(G, n), VelocityModel.RangeN(G).Lo, VelocityModel.RangeN(G).Hi, VelocityModel.Spread(G), notes, count, Bypassed());
+ plotInfo.Text = IsFixed() ? $"fixed {VelocityModel.Fixed(G)}"
+ : $"drive {VelocityModel.Drive(G):0.00} · {(VelocityModel.RandomOn(G) ? VelocityModel.RandomText(G) : "no")} random";
+ });
+ var axis = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto,*"), Height = 9 };
+ var a1 = Mono("in 1", AxisLbl, 7); var a2 = Mono("64", AxisLbl, 7); var a3 = Mono("127", AxisLbl, 7);
+ a3.HorizontalAlignment = HorizontalAlignment.Right;
+ Grid.SetColumn(a2, 1); Grid.SetColumn(a3, 2);
+ axis.Children.Add(a1); axis.Children.Add(a2); axis.Children.Add(a3);
+ var plot = new DockPanel { Margin = new Thickness(8, 6, 8, 4), Children = { WithDock(axis, Dock.Bottom), viz } };
+ axis.Margin = new Thickness(0, 2, 0, 0);
+ var transferIsland = IslandBox(IslandHead(Caps("TRANSFER"), plotInfo), plot, double.NaN);
+
+ // ---- OUT RANGE ----
+ var rangeTxt = Mono("", Txt, 8);
+ var range = new RangeSliderTrack
+ {
+ Reset = () => { Begin(POutLo); Begin(POutHi); S(POutLo, Def(POutLo)); S(POutHi, Def(POutHi)); End(POutLo); End(POutHi); Refresh(); },
+ };
+ range.GestureBegin += h => Begin(h == 0 ? POutLo : POutHi);
+ range.GestureEnd += h => End(h == 0 ? POutLo : POutHi);
+ range.Changed += (h, n) => { if (h == 0) SetLo(1 + n * 126); else SetHi(1 + n * 126); Refresh(); };
+ ToolTip.SetTip(range, "Out range — drag a handle, double-click resets to 1 – 127");
+ Learn(range, POutHi, "Out High");
+ readouts.Add(() =>
+ {
+ var (lo, hi) = VelocityModel.Range(G);
+ rangeTxt.Text = $"{lo} – {hi}";
+ if (!range.Dragging) { range.Lo = (lo - 1) / 126.0; range.Hi = (hi - 1) / 126.0; }
+ });
+
+ var rndSw = new SwitchTrack();
+ var rndLbl = Caps("RANDOM");
+ var rndVal = Mono("", Txt, 8); rndVal.HorizontalAlignment = HorizontalAlignment.Right;
+ var rndRow = new Border { Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand),
+ Child = new DockPanel { Children = { WithDock(rndVal, Dock.Right), new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Children = { rndSw, rndLbl } } } } };
+ rndRow.PointerPressed += (_, ev) =>
+ {
+ if (!ev.GetCurrentPoint(rndRow).Properties.IsLeftButtonPressed) return;
+ Set1(PRandomOn, VelocityModel.RandomOn(G) ? 0 : 1); Refresh(); ev.Handled = true;
+ };
+ ToolTip.SetTip(rndRow, "Random — spread each note's velocity (the amount is kept while it is off)");
+ Learn(rndRow, PRandomOn, "Random On");
+ var rndTrack = new SliderTrack { Height = 11, Reset = () => { Set1(PRandom, Def(PRandom)); Refresh(); } };
+ rndTrack.Changed += n => { S(PRandom, Math.Round(n * VelocityModel.RandomSpan) / VelocityModel.RandomSpan); Refresh(); };
+ rndTrack.GestureBegin += () => Begin(PRandom);
+ rndTrack.GestureEnd += () => End(PRandom);
+ ToolTip.SetTip(rndTrack, "Random amount, ±0 – 64 velocity — drag up / down, double-click resets");
+ Learn(rndTrack, PRandom, "Random");
+ var dirSeg = DeviceCardKit.Segments(Dirs, () => VelocityModel.Dir(G), i => { Set1(PRandomDir, i); Refresh(); }, out var dirSync,
+ fill: true, padX: 2, fontSize: 8);
+ ToolTip.SetTip(dirSeg, "Random both ways, only up, or only down");
+ Learn(dirSeg, PRandomDir, "Random Dir");
+ readouts.Add(() =>
+ {
+ bool on = VelocityModel.RandomOn(G);
+ rndSw.IsOn = on;
+ rndLbl.Foreground = on ? Txt : Cap;
+ rndVal.Foreground = on ? Txt : Cap;
+ rndVal.Text = VelocityModel.RandomText(G);
+ rndTrack.IsDim = !on;
+ if (!rndTrack.Dragging) rndTrack.Norm = Math.Clamp(G(PRandom), 0, 1);
+ dirSync();
+ });
+ var rndBox = new Border { BorderBrush = Rule, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 5, 0, 0),
+ Child = new StackPanel { Spacing = 5, Children = { rndRow, rndTrack, dirSeg } } };
+
+ var hist = new VelocityHistoryViz();
+ ToolTip.SetTip(hist, "The last 12 notes: outline — velocity in, fill — velocity out");
+ readouts.Add(() => hist.Set(notes, count, Bypassed()));
+ var histBox = new StackPanel { Spacing = 3, Children = { Caps("LAST 12 NOTES"), hist } };
+
+ var outBody = new DockPanel { Margin = new Thickness(8, 6), Children =
+ {
+ WithDock(histBox, Dock.Bottom),
+ new StackPanel { Spacing = 6, Children = { range, rndBox } },
+ } };
+ var outIsland = IslandBox(IslandHead(Caps("OUT RANGE"), rangeTxt), outBody, 160);
+
+ modeIsland.Margin = new Thickness(0, 0, 5, 0); outIsland.Margin = new Thickness(5, 0, 0, 0);
+ var islands = new DockPanel { Children = { WithDock(modeIsland, Dock.Left), WithDock(outIsland, Dock.Right), transferIsland } };
+
+ var statusL = new TextBlock { FontSize = 8, Foreground = Sub, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var statusR = Mono("", Sub);
+ readouts.Add(() =>
+ {
+ var (lo, hi) = VelocityModel.Range(G);
+ string rnd = VelocityModel.RandomOn(G) ? $"{VelocityModel.RandomText(G)} {Dirs[VelocityModel.Dir(G)].ToLowerInvariant()}" : "off";
+ statusL.Text = $"{Modes[Mode()]} · {(IsFixed() ? "value " + VelocityModel.Fixed(G) : $"drive {VelocityModel.Drive(G):0.00}")} · random {rnd} · out {lo}–{hi}";
+ statusR.Text = Bypassed() ? "bypassed" : Last() is { } l ? $"last {l.In} → {l.Out}" : "MIDI";
+ });
+ return Framed(islands, statusL, statusR);
}
- Control Seg(int p, string[] names, Action<int>? extra = null, double fs = 9, double padX = 7)
+
+ // =========================================================================================
+ Control BuildMini()
{
- var seg = DeviceCardKit.Segments(names, () => Math.Clamp(Gi(p), 0, names.Length - 1), iv => { S(p, iv); extra?.Invoke(iv); Refresh(); }, out var sync);
- readouts.Add(sync);
- MidiLearn.Bind(seg, MidiTarget.MidiDeviceParam(track, mi, p), engine.MidiEffectParamName(track, mi, p));
- return seg;
+ // Mode chip: click for the next mode, Shift-click for the previous.
+ var modeTb = new TextBlock { FontSize = 9, Foreground = Txt, VerticalAlignment = VerticalAlignment.Center };
+ var chev = new Glyph(GlyphKind.ChevronDown, 7) { Foreground = Cap, VerticalAlignment = VerticalAlignment.Center };
+ var modeChip = new Border { Height = 14, Width = 70, CornerRadius = NotaRadius.Badge, Background = NotaPalette.GridBeat, BorderBrush = Bd, BorderThickness = new Thickness(1),
+ Padding = new Thickness(6, 0), Cursor = new Cursor(StandardCursorType.Hand), Margin = new Thickness(0, 0, 6, 0),
+ Child = new DockPanel { Children = { WithDock(chev, Dock.Right), modeTb } } };
+ modeChip.PointerPressed += (_, ev) =>
+ {
+ if (!ev.GetCurrentPoint(modeChip).Properties.IsLeftButtonPressed) return;
+ int d = ev.KeyModifiers.HasFlag(KeyModifiers.Shift) ? 2 : 1;
+ Set1(PMode, (Mode() + d) % 3); Refresh(); ev.Handled = true;
+ };
+ ToolTip.SetTip(modeChip, "Velocity mode: Curve / Compand / Fixed — click for the next, Shift-click for the previous");
+ Learn(modeChip, PMode, "Mode");
+ var hint = Mono("", Cap, 7); hint.HorizontalAlignment = HorizontalAlignment.Right;
+ var head = new DockPanel { Height = 14, Children = { WithDock(modeChip, Dock.Left), hint } };
+
+ var viz = new VelocityTransferViz { Full = false };
+ ToolTip.SetTip(viz, "Input across, output up · dashed — the Out range · band — Random · dots — the last notes");
+ var lastIO = Mono("", BrassLit, 7);
+ lastIO.HorizontalAlignment = HorizontalAlignment.Right; lastIO.VerticalAlignment = VerticalAlignment.Top; lastIO.Margin = new Thickness(0, 3, 5, 0);
+ lastIO.IsHitTestVisible = false;
+ var plot = new Panel { Margin = new Thickness(0, 4), Children = { viz, lastIO } };
+
+ var knobs = new Grid { Height = 53, ColumnDefinitions = new ColumnDefinitions("*,*,*,*") };
+ var cells = new[]
+ {
+ KnobCell(DriveLabel, DriveParam, DriveNorm, DriveSet, () => VelocityModel.DriveText(G), () => IsFixed() ? (Def(PFixed) * 127 - 1) / 126 : VelocityModel.DriveNorm(Def(PDrive))),
+ KnobCell(() => "RANDOM", () => PRandom, () => Math.Clamp(G(PRandom), 0, 1), n =>
+ {
+ S(PRandom, Math.Round(n * VelocityModel.RandomSpan) / VelocityModel.RandomSpan);
+ if (!VelocityModel.RandomOn(G)) S(PRandomOn, 1); // turning Random up switches it on
+ }, () => VelocityModel.RandomOn(G) ? VelocityModel.RandomText(G) : "off", () => Def(PRandom), dim: () => !VelocityModel.RandomOn(G)),
+ KnobCell(() => "LOW", () => POutLo, () => (VelocityModel.Range(G).Lo - 1) / 126.0, n => SetLo(1 + n * 126), () => VelocityModel.Range(G).Lo.ToString(), () => 0),
+ KnobCell(() => "HIGH", () => POutHi, () => (VelocityModel.Range(G).Hi - 1) / 126.0, n => SetHi(1 + n * 126), () => VelocityModel.Range(G).Hi.ToString(), () => 1),
+ };
+ for (int i = 0; i < cells.Length; i++) { Grid.SetColumn(cells[i], i); knobs.Children.Add(cells[i]); }
+
+ var inner = new DockPanel { Children = { WithDock(head, Dock.Top), WithDock(knobs, Dock.Bottom), plot } };
+ var island = new Border { Background = Island, BorderBrush = Bd, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile,
+ Padding = new Thickness(6, 5, 6, 0), Child = inner };
+ readouts.Add(() =>
+ {
+ modeTb.Text = Modes[Mode()];
+ hint.Text = VelocityModel.DriveHint(G);
+ viz.Set(n => VelocityModel.Base(G, n), VelocityModel.RangeN(G).Lo, VelocityModel.RangeN(G).Hi, VelocityModel.Spread(G), notes, count, Bypassed());
+ lastIO.Text = Last() is { } l ? $"{l.In} → {l.Out}" : "";
+ });
+
+ // Footer: "random both" steps Both → Up → Down → off → Both (Shift-click backwards).
+ var statusL = new TextBlock { FontSize = 8, Foreground = Sub, VerticalAlignment = VerticalAlignment.Center, Cursor = new Cursor(StandardCursorType.Hand), Background = Brushes.Transparent };
+ statusL.PointerEntered += (_, _) => statusL.Foreground = Txt;
+ statusL.PointerExited += (_, _) => statusL.Foreground = Sub;
+ statusL.PointerPressed += (_, ev) =>
+ {
+ if (!ev.GetCurrentPoint(statusL).Properties.IsLeftButtonPressed) return;
+ int state = VelocityModel.RandomOn(G) ? VelocityModel.Dir(G) : 3; // 0 both · 1 up · 2 down · 3 off
+ state = (state + (ev.KeyModifiers.HasFlag(KeyModifiers.Shift) ? 3 : 1)) % 4;
+ Begin(PRandomOn); Begin(PRandomDir);
+ if (state == 3) S(PRandomOn, 0); else { S(PRandomOn, 1); S(PRandomDir, state); }
+ End(PRandomOn); End(PRandomDir);
+ Refresh(); ev.Handled = true;
+ };
+ ToolTip.SetTip(statusL, "Random: both ways → up → down → off — click to step, Shift-click back");
+ Learn(statusL, PRandomDir, "Random Dir");
+ var statusR = Mono("", Sub);
+ readouts.Add(() =>
+ {
+ statusL.Text = VelocityModel.RandomOn(G) ? $"random {Dirs[VelocityModel.Dir(G)].ToLowerInvariant()}" : "random off";
+ var (lo, hi) = VelocityModel.Range(G);
+ statusR.Text = Bypassed() ? "bypassed" : $"out {lo} – {hi}";
+ });
+ return Framed(island, statusL, statusR);
}
- // ---- LIVE strip: mode + contextual controls ----
- var stripHost = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center };
- void BuildStrip()
+ // ---- shared pieces -----------------------------------------------------------------------
+ Control Framed(Control main, TextBlock left, TextBlock right)
{
- stripHost.Children.Clear();
- int mode = Gi(PMode);
- if (mode == 2) stripHost.Children.Add(MiniSlider("FIXED", PFixed, 0, 1, v => $"{v * 127:0}", 54));
- else stripHost.Children.Add(MiniSlider("DRIVE", PDrive, 0.05, 2, v => $"{v:0.00}", 54));
- stripHost.Children.Add(MiniSlider("RANDOM", PRandom, 0, 1, v => $"±{v * 0.5 * 127:0}", 48));
+ var status = new Border { Height = 18, Background = Well, BorderBrush = Bd, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(8, 0),
+ Child = new DockPanel { Children = { WithDock(right, Dock.Right), left } } };
+ right.Margin = new Thickness(8, 0, 0, 0);
+ return new DockPanel { Background = Ground, Children = { WithDock(status, Dock.Bottom), new Border { Padding = new Thickness(5), Child = main } } };
}
- var modeSeg = Seg(PMode, Modes, _ => BuildStrip());
- var liveStrip = new Border { Height = 34, Background = HdrBg, BorderBrush = Bd, BorderThickness = new Thickness(0, 0, 0, 1), Padding = new Thickness(9, 0),
- Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center, Children = { modeSeg, stripHost } } };
-
- // ---- TRANSFER panel ----
- var viz = new VelocityCurveViz { VerticalAlignment = VerticalAlignment.Stretch };
- var scope = new float[24];
- var readout = Mono("", AmberLit); readout.HorizontalAlignment = HorizontalAlignment.Right;
- var transHead = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), Height = 11 };
- Grid.SetColumn(readout, 1); transHead.Children.Add(Cap("TRANSFER")); transHead.Children.Add(readout);
- var axis = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), Height = 10 };
- var ax1 = Mono("64", NotaPalette.TextDisabled, 8); ax1.HorizontalAlignment = HorizontalAlignment.Center;
- var ax2 = Mono("out 127", NotaPalette.TextDisabled, 8); ax2.HorizontalAlignment = HorizontalAlignment.Right;
- Grid.SetColumn(ax1, 1); Grid.SetColumn(ax2, 2);
- axis.Children.Add(Mono("in 1", NotaPalette.TextDisabled, 8)); axis.Children.Add(ax1); axis.Children.Add(ax2);
- var transDock = new DockPanel { LastChildFill = true };
- DockPanel.SetDock(transHead, Dock.Top); DockPanel.SetDock(axis, Dock.Bottom);
- transDock.Children.Add(transHead); transDock.Children.Add(axis); transDock.Children.Add(viz);
- var transPanel = new Border { Background = Inset, BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Panel, Padding = new Thickness(8, 4), Margin = new Thickness(8, 7), Child = transDock };
-
- readouts.Add(() =>
+
+ Control IslandHead(Control left, Control? right)
{
- int n = engine.MidiEffectScope(track, mi, scope);
- var dots = new List<(double, double)>();
- for (int k = 0; k + 1 < n; k += 2) dots.Add((scope[k], scope[k + 1]));
- int li = engine.MidiEffectLastIn(track, mi), lo = engine.MidiEffectLastOut(track, mi);
- (double, double)? last = li >= 0 ? (li / 127.0, lo / 127.0) : null;
- viz.Set(Transfer, dots, last);
- double dev = G(PRandom) * 0.5 * 127;
- readout.Text = Gi(PMode) == 2 ? $"fixed {G(PFixed) * 127:0} · ±{dev:0}"
- : $"drive {Math.Clamp(G(PDrive), 0.05, 2):0.00} · ±{dev:0} random";
- });
-
- // ---- right rail ----
- // OUT RANGE — a dual-handle range bar over [POutLo, POutHi], shown as 1..127.
- var rangeVals = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto") };
- var loT = Mono("", Txt); var hiT = Mono("", Txt); hiT.HorizontalAlignment = HorizontalAlignment.Right;
- Grid.SetColumn(hiT, 2); rangeVals.Children.Add(loT); rangeVals.Children.Add(hiT);
- var rangeFill = new Border { Background = NotaPalette.Wash(NotaPalette.Accent, 0x73), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Stretch };
- var rangeBar = new Panel { Height = 8, Background = Inset, Cursor = new Cursor(StandardCursorType.Hand) };
- rangeBar.Children.Add(rangeFill);
- var rangeClip = new Border { Height = 8, CornerRadius = NotaRadius.Control, ClipToBounds = true, Child = rangeBar };
- int rDrag = 0; // 1 = lo, 2 = hi
- void RangeVis() { double W = rangeBar.Bounds.Width, lo = G(POutLo), hi = G(POutHi); rangeFill.Margin = new Thickness(lo * W, 0, 0, 0); rangeFill.Width = Math.Max(0, (hi - lo) * W); loT.Text = $"{Math.Max(1, lo * 127):0}"; hiT.Text = $"{hi * 127:0}"; }
- void RangeX(double x) { double n = Math.Clamp(x / Math.Max(1, rangeBar.Bounds.Width), 0, 1); if (rDrag == 1) S(POutLo, Math.Min(n, G(POutHi))); else S(POutHi, Math.Max(n, G(POutLo))); RangeVis(); Refresh(); }
- rangeBar.PointerPressed += (_, e) => { double x = e.GetPosition(rangeBar).X, n = x / Math.Max(1, rangeBar.Bounds.Width); rDrag = Math.Abs(n - G(POutLo)) <= Math.Abs(n - G(POutHi)) ? 1 : 2; e.Pointer.Capture(rangeBar); RangeX(x); };
- rangeBar.PointerMoved += (_, e) => { if (rDrag > 0) RangeX(e.GetPosition(rangeBar).X); };
- rangeBar.PointerReleased += (_, e) => { if (rDrag > 0) { rDrag = 0; e.Pointer.Capture(null); } };
- rangeBar.SizeChanged += (_, _) => RangeVis();
- readouts.Add(() => { if (rDrag == 0) RangeVis(); });
-
- // RANDOM ON toggle (amount lives in the strip; this gates it, remembering the amount).
- var rndToggle = DeviceCardKit.Switch("Random", () => G(PRandom) > 0,
- () => { if (G(PRandom) > 0) S(PRandom, 0); else S(PRandom, lastRnd > 0 ? lastRnd : 0.2); Refresh(); }, out var rndSync);
- readouts.Add(rndSync);
-
- var dirRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = { Cap("MODE"), Seg(PRandomDir, Dirs, null, 8, 6) } };
-
- // LAST 12 NOTES histogram.
- var bars = new Border[12];
- var barRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2, Height = 22, VerticalAlignment = VerticalAlignment.Bottom };
- for (int i = 0; i < 12; i++) { bars[i] = new Border { Width = 9, CornerRadius = NotaRadius.Bar, VerticalAlignment = VerticalAlignment.Bottom, Background = AmberDim, Height = 2 }; barRow.Children.Add(bars[i]); }
- readouts.Add(() =>
+ var d = new DockPanel { Margin = new Thickness(8, 0) };
+ if (right is not null) { right.HorizontalAlignment = HorizontalAlignment.Right; d.Children.Add(WithDock(right, Dock.Right)); }
+ d.Children.Add(left);
+ return new Border { Height = 20, BorderBrush = Bd, BorderThickness = new Thickness(0, 0, 0, 1), Child = d };
+ }
+
+ Border IslandBox(Control head, Control content, double width)
{
- for (int i = 0; i < 12; i++)
- {
- double v = i * 2 + 1 < scope.Length ? scope[i * 2 + 1] : 0; // output velocity
- bars[i].Height = Math.Max(2, v * 22);
- bool newest = i == 11;
- bars[i].Background = v <= 0.001 ? Inset : newest ? AmberLit : AmberDim;
- }
- });
- var histBlock = new StackPanel { Spacing = 3, Children = { Cap("LAST 12 NOTES"), barRow } };
+ var b = new Border { Background = Island, BorderBrush = Bd, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, ClipToBounds = true,
+ Child = new DockPanel { Children = { WithDock(head, Dock.Top), content } } };
+ if (!double.IsNaN(width)) b.Width = width;
+ return b;
+ }
- var rail = new StackPanel { Spacing = 5, Children =
+ // A mini-view knob: 34px gauge, caps label, mono value. Label and target param may follow the mode (DRIVE / VALUE).
+ Control KnobCell(Func<string> label, Func<int> param, Func<double> norm, Action<double> set, Func<string> text, Func<double> resetNorm, Func<bool>? dim = null)
{
- Cap("OUT RANGE"), rangeClip, rangeVals,
- new Border { Height = 1, Background = NotaPalette.SurfaceRaised, Margin = new Thickness(0, 1) },
- rndToggle, dirRow,
- } };
- var railDock = new DockPanel { LastChildFill = false, VerticalAlignment = VerticalAlignment.Stretch };
- DockPanel.SetDock(rail, Dock.Top); DockPanel.SetDock(histBlock, Dock.Bottom);
- railDock.Children.Add(rail); railDock.Children.Add(histBlock);
- var railBorder = new Border { Width = 160, Background = RailBg, BorderBrush = Bd, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(8, 6), Child = railDock };
-
- var body = new DockPanel { LastChildFill = true };
- DockPanel.SetDock(railBorder, Dock.Right); body.Children.Add(railBorder); body.Children.Add(transPanel);
- var root = new DockPanel { LastChildFill = true, Background = NotaPalette.BgApp };
- DockPanel.SetDock(liveStrip, Dock.Top); root.Children.Add(liveStrip); root.Children.Add(body);
-
- BuildStrip();
- ctx.AddDeviceRefresher(Refresh); // curve dots + histogram follow playback
- Refresh();
- return root;
+ var knob = new Knob(norm(), 1.0) { Accent = true, Width = 34, Height = 34, HorizontalAlignment = HorizontalAlignment.Center, Default = resetNorm() };
+ int gesture = -1;
+ knob.ValueChanged += n => { set(n); Refresh(); };
+ knob.GestureBegin += () => { gesture = param(); Begin(gesture); if (gesture == PRandom) Begin(PRandomOn); };
+ knob.GestureEnd += () => { if (gesture >= 0) End(gesture); if (gesture == PRandom) End(PRandomOn); gesture = -1; };
+ Learn(knob, param(), label());
+ var lbl = new TextBlock { FontSize = 7, FontWeight = FontWeight.Bold, LetterSpacing = 0.6, Foreground = Cap, HorizontalAlignment = HorizontalAlignment.Center, LineHeight = 9 };
+ var v = Mono("", Sub, 7); v.HorizontalAlignment = HorizontalAlignment.Center;
+ readouts.Add(() =>
+ {
+ double n = norm();
+ if (!knob.Dragging && Math.Abs(knob.Value - n) > 1e-6) knob.Value = n;
+ knob.Default = resetNorm();
+ knob.IsDim = dim?.Invoke() ?? false;
+ lbl.Text = label(); v.Text = text();
+ });
+ return new StackPanel { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Cursor = new Cursor(StandardCursorType.SizeNorthSouth),
+ Children = { knob, lbl, v } };
+ }
}
}
diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs
index b5f2f12b..aeafc866 100644
--- a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs
+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs
@@ -1152,7 +1152,8 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)
body.Children.Add(new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Children = { ActionChip("Save preset", () => _ctx.RequestRackPresetSave(sc)) } });
int pc = a.ChainInstrumentParamCount(sc);
if (pc == 0) body.Children.Add(new TextBlock { Text = "No parameters", FontSize = 9, Foreground = TextTertiary });
- for (int p = 0; p < pc; p++) body.Children.Add(RackInstParamRow(a, sc, p));
+ for (int p = 0; p < pc; p++)
+ if (a.ChainInstrumentParamName(sc, p) != "View") body.Children.Add(RackInstParamRow(a, sc, p)); // the card size isn't sound
Control fullBtn;
if (ik == -1) fullBtn = ActionChip("Full", () => { try { E.RackOpenChainInstrumentEditor(T, sc); } catch { /* no-op */ } });
diff --git a/src/managed/Nota.App/DeviceChainView.Instruments.cs b/src/managed/Nota.App/DeviceChainView.Instruments.cs
index 5b6cbc6c..37b1d383 100644
--- a/src/managed/Nota.App/DeviceChainView.Instruments.cs
+++ b/src/managed/Nota.App/DeviceChainView.Instruments.cs
@@ -22,13 +22,16 @@ public sealed partial class DeviceChainView
// else (or a synth reporting no params) → the generic Open-GUI card.
bool hasParams = _engine.PluginParamCount(_trackId, -1) > 0;
var strategy = _instrumentFactory.Resolve(kind, hasParams);
- var body = strategy.Build(NewCardContext());
+ var ctx = NewCardContext();
+ var body = strategy.Build(ctx);
if (!strategy.BodyOnly) return body; // card owns its whole frame (not yet migrated)
+ double width = strategy.WidthFor(_engine, _trackId);
var spec = new ShellSpec(
Name: _engine.DeviceName(_trackId, -1), Subtitle: strategy.Subtitle, DeviceIndex: -1, Count: 1,
Bypassed: false, Bypassable: false, CanMove: false, CanDelete: false,
- PresetKind: kind, IsInstrument: true, Width: strategy.CardWidth, Kind: ChainKind.Instrument,
- VoiceLabel: strategy.VoiceLabel, Presets: kind == Nota.Application.RhythmModel.Kind ? KitPresets() : null);
+ PresetKind: kind, IsInstrument: true, Width: width, Kind: ChainKind.Instrument,
+ VoiceLabel: strategy.VoiceLabel, Presets: kind == Nota.Application.RhythmModel.Kind ? KitPresets() : null,
+ HeaderExtra: strategy.HeaderAccessory(ctx), Compact: width < 300);
return BuildCardShell(spec, body);
}
diff --git a/src/managed/Nota.App/DeviceChainView.Shell.cs b/src/managed/Nota.App/DeviceChainView.Shell.cs
index 9e40eab4..c5b5bd4b 100644
--- a/src/managed/Nota.App/DeviceChainView.Shell.cs
+++ b/src/managed/Nota.App/DeviceChainView.Shell.cs
@@ -85,7 +85,11 @@ public sealed partial class DeviceChainView
private float[] CaptureParams(ChainKind k, int di)
{ int n = ParamCount(k, di); var a = new float[n]; for (int i = 0; i < n; i++) a[i] = GetP(k, di, i); return a; }
private void ApplyParams(ChainKind k, int di, float[] p)
- { int n = Math.Min(p.Length, ParamCount(k, di)); for (int i = 0; i < n; i++) SetPr(k, di, i, p[i]); }
+ {
+ int n = Math.Min(p.Length, ParamCount(k, di));
+ int view = k == ChainKind.Instrument ? Nota.Application.InstrumentView.Index(_engine, _trackId) : -1; // A/B keeps the card size
+ for (int i = 0; i < n; i++) if (i != view) SetPr(k, di, i, p[i]);
+ }
internal readonly record struct ShellSpec(
string Name, string Subtitle, int DeviceIndex, int Count, bool Bypassed, bool Bypassable,
diff --git a/src/managed/Nota.Application/Instruments/InstrumentView.cs b/src/managed/Nota.Application/Instruments/InstrumentView.cs
new file mode 100644
index 00000000..5363eb3d
--- /dev/null
+++ b/src/managed/Nota.Application/Instruments/InstrumentView.cs
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The S / L card size of a built-in instrument that comes in two sizes (Nota Synth). The
+// size is the instrument's own "view" param (0 = L, 1 = S), so it saves with the project's
+// state blob and follows a duplicated track; its default in the engine is the instrument's
+// default size. It is editor state, not sound: presets neither save nor apply it and it is
+// not offered for automation.
+
+namespace Nota.Application;
+
+public static class InstrumentView
+{
+ public const string ParamId = "view";
+
+ /// <summary>True for the param id that holds the card size — skip it wherever params
+ /// are treated as the sound (presets, automation targets, generic knob lists).</summary>
+ public static bool IsViewParam(string id) => id == ParamId;
+
+ /// <summary>The index of the instrument's view param, or -1 when it has only one size.</summary>
+ public static int Index(IAudioEngine engine, int trackId)
+ {
+ int pc = engine.PluginParamCount(trackId, -1);
+ for (int i = pc - 1; i >= 0; i--)
+ if (engine.PluginParamId(trackId, -1, i) == ParamId) return i;
+ return -1;
+ }
+
+ /// <summary>True when the instrument's card is set to the mini (S) size.</summary>
+ public static bool IsMini(IAudioEngine engine, int trackId)
+ => Index(engine, trackId) is var i and >= 0 && engine.PluginParamGet(trackId, -1, i) >= 0.5f;
+
+ public static void SetMini(IAudioEngine engine, int trackId, bool mini)
+ {
+ if (Index(engine, trackId) is var i and >= 0) engine.PluginParamSet(trackId, -1, i, mini ? 1f : 0f);
+ }
+}
diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
index 8fd1006d..9e09363f 100644
--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
@@ -2272,11 +2272,42 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
Len("Legato Glide", mode: 0, div: 3, legato: true);
Len("Legato Bar Pad", mode: 0, div: 5, legato: true, clip: true);
Len("Clip-Safe Quarter", mode: 0, div: 3, clip: true, rnd: 0.1f);
- // ---- Nota Velocity (MIDI, kind 4) — Mode 0 Curve/1 Compand/2 Fixed; Drive 1 = linear
- Midi("velocity", 4, "Soft Hands", ("Mode", 0f), ("Drive", 1.4f));
- Midi("velocity", 4, "Humanize", ("Mode", 0f), ("Drive", 1f), ("Random", 0.25f));
- Midi("velocity", 4, "Compress", ("Mode", 1f), ("Drive", 0.6f));
- Midi("velocity", 4, "Fixed 100", ("Mode", 2f), ("Fixed", 0.79f));
+ // ---- Nota Velocity (MIDI, kind 4) — almanac rework. Mode 0 Curve / 1 Compand / 2 Fixed;
+ // drive 0.25..4 (1 = linear; Curve > 1 lifts soft notes, Compand > 1 stretches to the edges);
+ // value / Out range as MIDI velocities 1..127; Random ±0..64, dir 0 Both / 1 Up / 2 Down,
+ // off unless rnd is given.
+ Vel("Init");
+ Vel("Humanize", rnd: 16);
+ Vel("Humanize Subtle", rnd: 6);
+ Vel("Humanize Loose", rnd: 28);
+ Vel("Soft Hands", drive: 1.4f);
+ Vel("Light Touch", drive: 2f);
+ Vel("Feather", drive: 3f, lo: 30, hi: 110);
+ Vel("Heavy Hands", drive: 0.6f);
+ Vel("Hard Hitter", drive: 0.35f);
+ Vel("Stiff Keyboard Fix", drive: 1.8f, lo: 20);
+ Vel("Soft Pedal", drive: 1.2f, hi: 90);
+ Vel("Gentle Compress", mode: 1, drive: 0.7f);
+ Vel("Tight Compress", mode: 1, drive: 0.45f);
+ Vel("Squash", mode: 1, drive: 0.3f, lo: 60, hi: 110);
+ Vel("Expand Dynamics", mode: 1, drive: 1.6f);
+ Vel("Accent Maker", mode: 1, drive: 2.5f);
+ Vel("Mid Band", mode: 1, lo: 50, hi: 90);
+ Vel("Fixed 127", mode: 2, value: 127);
+ Vel("Fixed 100", mode: 2, value: 100);
+ Vel("Fixed 64", mode: 2, value: 64);
+ Vel("Ghost 30", mode: 2, value: 30);
+ Vel("Drum Machine", mode: 2, value: 100, rnd: 6);
+ Vel("Accent Lottery", mode: 2, value: 90, rnd: 30, dir: 1);
+ Vel("Pad Floor", lo: 40, hi: 100);
+ Vel("Quiet Layer", hi: 60);
+ Vel("Loud Only", lo: 90);
+ Vel("Push Up", rnd: 20, dir: 1);
+ Vel("Pull Down", rnd: 20, dir: 2);
+ Vel("Ghost Notes", drive: 0.5f, lo: 10, hi: 70, rnd: 8);
+ Vel("Loose Soft Hands", drive: 1.5f, rnd: 12);
+ Vel("Tight Groove", mode: 1, drive: 0.5f, lo: 70, hi: 115, rnd: 5);
+ Vel("Chaos", rnd: 64);
// ---- Nota Random (MIDI, kind 5) — almanac rework. Note ±0..12 st; Vel / Time / Skip / Oct
// amounts 0..1 (±64 velocity, ≤100 ms late, 0..100 % dropped, ±2 octaves); Dist 0 Gauss /
// 1 Even / 2 Walk; Rate 0 per note / 1 per bar. A locked preset carries its seed, so the
@@ -2542,6 +2573,12 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
=> Midi("notelength", 3, name, ("Mode", mode), ("Division", div), ("Ms", ms), ("Percent", pct), ("Trigger", trig),
("Vel to Len", vel), ("Key to Len", key), ("Random", rnd), ("Legato", legato ? 1 : 0), ("Clip Limit", clip ? 1 : 0), ("Gate", 1));
+ // A Nota Velocity preset (MIDI kind 4) in musical units; every sound param is named so switching
+ // presets is exact.
+ private void Vel(string name, int mode = 0, float drive = 1f, int value = 100, int lo = 1, int hi = 127, int rnd = 0, int dir = 0)
+ => Midi("velocity", 4, name, ("Mode", mode), ("Drive", drive), ("Fixed", value / 127f), ("Out Low", lo / 127f), ("Out High", hi / 127f),
+ ("Random", rnd > 0 ? rnd / 64f : 0.25f), ("Random Dir", dir), ("Random On", rnd > 0 ? 1 : 0));
+
// A Nota Random preset (MIDI kind 5); every sound param is named so switching presets is exact.
// seed > 0 locks the roll on that seed (bar 0's roll repeats every bar).
private void Rnd(string name, float chance, float note = 0, float vel = 0, float time = 0, float skip = 0, float oct = 0,
diff --git a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs b/src/managed/Nota.Infrastructure/Persistence/PresetService.cs
index 9d09e45a..c7969595 100644
--- a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/PresetService.cs
@@ -49,7 +49,11 @@ public static class PresetService
doc.BuiltinKind = ik;
doc.NamedParams = new Dictionary<string, float>(pc);
for (int i = 0; i < pc; i++)
- doc.NamedParams[engine.PluginParamId(trackId, -1, i)] = engine.PluginParamGet(trackId, -1, i);
+ {
+ string id = engine.PluginParamId(trackId, -1, i);
+ if (InstrumentView.IsViewParam(id)) continue; // the card size is editor state, not sound
+ doc.NamedParams[id] = engine.PluginParamGet(trackId, -1, i);
+ }
return doc;
}
}
@@ -148,6 +152,14 @@ public static class PresetService
engine.MidiEffectSetParam(trackId, index, 7, -engine.MidiEffectGetParam(trackId, index, 7));
}
+ /// <summary>Nota Velocity (MIDI kind 4) before the almanac rework had no Random switch — any
+ /// Random amount was live. Turns the switch on when the old amount was above zero.</summary>
+ public static void VelocityLegacy(IAudioEngine engine, int trackId, int index)
+ {
+ if (engine.MidiEffectParamCount(trackId, index) < 8) return;
+ engine.MidiEffectSetParam(trackId, index, 7, engine.MidiEffectGetParam(trackId, index, 3) > 0f ? 1f : 0f);
+ }
+
private static void LegacyRange(PresetDocument doc, IAudioEngine engine, int trackId, int deviceIndex)
{
if (doc.BuiltinKind != 16 || engine.DeviceParamCount(trackId, deviceIndex) <= 10) return;
@@ -190,6 +202,7 @@ public static class PresetService
engine.MidiEffectSetParam(targetTrackId, mi, i, v);
if (doc.BuiltinKind == 1 && !doc.NamedParams.ContainsKey("On 1")) ChordLegacySwitches(engine, targetTrackId, mi);
if (doc.BuiltinKind == 3 && doc.NamedParams.ContainsKey("Rate") && !doc.NamedParams.ContainsKey("Division")) LengthLegacy(engine, targetTrackId, mi);
+ if (doc.BuiltinKind == 4 && !doc.NamedParams.ContainsKey("Random On")) VelocityLegacy(engine, targetTrackId, mi);
}
return "";
}
@@ -217,7 +230,8 @@ public static class PresetService
{
int pc = engine.PluginParamCount(t, -1);
for (int i = 0; i < pc; i++)
- if (doc.NamedParams.TryGetValue(engine.PluginParamId(t, -1, i), out var v))
+ if (engine.PluginParamId(t, -1, i) is var pid && !InstrumentView.IsViewParam(pid)
+ && doc.NamedParams.TryGetValue(pid, out var v))
engine.PluginParamSet(t, -1, i, v);
}
return "";
@@ -265,6 +279,7 @@ public static class PresetService
for (int i = 0; i < pc; i++)
{
string id = engine.PluginParamId(trackId, -1, i);
+ if (InstrumentView.IsViewParam(id)) continue; // a preset keeps the card's S / L size
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;
@@ -315,6 +330,9 @@ public static class PresetService
// A Nota Length preset from before Division: map its Rate (and Key to Len's old sign).
if (engine.MidiEffectKind(trackId, deviceIndex) == 3 && doc.NamedParams.ContainsKey("Rate") && !doc.NamedParams.ContainsKey("Division"))
LengthLegacy(engine, trackId, deviceIndex);
+ // A Nota Velocity preset from before the Random switch: its amount was always live.
+ if (engine.MidiEffectKind(trackId, deviceIndex) == 4 && !doc.NamedParams.ContainsKey("Random On"))
+ VelocityLegacy(engine, trackId, deviceIndex);
}
return "";
}
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
index e87b7b8d..12702d77 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
@@ -607,6 +607,7 @@ public sealed class ProjectService
for (int p = 0; p < m.Params.Length && p < mpc; p++) engine.MidiEffectSetParam(id, mi, p, m.Params[p]);
if (m.Kind == 1 && m.Params.Length <= 16) PresetService.ChordLegacySwitches(engine, id, mi); // pre-switch Nota Chord
if (m.Kind == 3 && m.Params.Length <= 11) PresetService.LengthLegacy(engine, id, mi); // pre-Division Nota Length
+ if (m.Kind == 4 && m.Params.Length <= 7) PresetService.VelocityLegacy(engine, id, mi); // pre-switch Nota Velocity
if (m.Bypassed) engine.SetMidiEffectBypassed(id, mi, true);
if (m.CcDestDevice >= 0 && m.CcDestParam >= 0)
{
diff --git a/src/managed/Nota.Mcp/Tools/MidiFxTools.cs b/src/managed/Nota.Mcp/Tools/MidiFxTools.cs
index 9ae28717..061dd984 100644
--- a/src/managed/Nota.Mcp/Tools/MidiFxTools.cs
+++ b/src/managed/Nota.Mcp/Tools/MidiFxTools.cs
@@ -500,6 +500,98 @@ public sealed class MidiFxTools(IAudioEngine engine, IEngineDispatch dispatch, I
if (view is not null) S(LView, view.Trim().Equals("S", StringComparison.OrdinalIgnoreCase) ? 1 : 0);
});
+ // ---- Nota Velocity (kind 4) — named access in musical units ------------------------------
+ // Param layout mirrors MidiVelocity.h: Drive 0, Fixed 1, Out Low 2, Random 3, Mode 4, Out High 5,
+ // Random Dir 6, Random On 7, View 8.
+ private const int VDrive = 0, VFixed = 1, VLo = 2, VRnd = 3, VMode = 4, VHi = 5, VDir = 6, VRndOn = 7, VView = 8;
+ private static readonly string[] VelModes = { "curve", "compand", "fixed" };
+ private static readonly string[] VelDirs = { "both", "up", "down" };
+
+ public sealed record VelocityNote(int In, int Out);
+ public sealed record VelocityState(
+ string Mode, float Drive, int FixedValue, int OutLow, int OutHigh, bool RandomOn, int RandomAmount, string RandomDirection,
+ string View, int[] Curve, VelocityNote[] LastNotes, int NotesShaped);
+
+ private void RequireVelocity(int trackId, int index)
+ {
+ if (E.MidiEffectKind(trackId, index) != 4 || E.MidiEffectParamCount(trackId, index) <= VView)
+ throw new ArgumentException($"MIDI effect {index} on track {trackId} is not a Nota Velocity.");
+ }
+
+ [McpServerTool(Name = "get_velocity"), Description(
+ "Read a Nota Velocity (MIDI effect kind 4) in musical units: mode (curve | compand | fixed), drive 0.25..4 (1 = linear; "
+ + "curve: > 1 makes soft notes louder, < 1 quieter; compand: > 1 stretches velocities to the edges, < 1 squeezes them to the "
+ + "middle), fixedValue 1..127 (fixed mode), the Out range outLow..outHigh (1..127), randomOn, randomAmount 0..64 (velocity "
+ + "units), randomDirection (both | up | down), card view, curve — the output before Random for inputs 1, 16, 32 … 127 "
+ + "(9 points) — and live telemetry: the last (up to 12) notes as in → out velocity, oldest first, and notes shaped so far.")]
+ public Task<VelocityState> GetVelocity(int trackId, int index) => Read(() =>
+ {
+ RequireVelocity(trackId, index);
+ float G(int p) => E.MidiEffectGetParam(trackId, index, p);
+ int V(float n) => Math.Clamp((int)MathF.Round(n * 127), 1, 127);
+ int mode = Math.Clamp((int)MathF.Round(G(VMode)), 0, 2);
+ float drive = Math.Clamp(G(VDrive), 0.05f, 4f);
+ float lo = Math.Clamp(G(VLo), 0, 1), hi = Math.Clamp(G(VHi), 0, 1);
+ if (lo > hi) (lo, hi) = (hi, lo);
+ lo = MathF.Max(lo, 1 / 127f); hi = MathF.Max(hi, 1 / 127f);
+ int[] ins = { 1, 16, 32, 48, 64, 80, 96, 112, 127 };
+ var curve = Array.ConvertAll(ins, v =>
+ {
+ double n = v / 127.0, shaped;
+ if (mode == 2) shaped = Math.Clamp(G(VFixed), 0, 1);
+ else if (mode == 1) { double c = 2 * n - 1; shaped = Math.Clamp(0.5 + Math.Sign(c) * Math.Pow(Math.Abs(c), 1 / drive) * 0.5, 0, 1); }
+ else shaped = Math.Pow(n, 1 / drive);
+ return V((float)(lo + shaped * (hi - lo)));
+ });
+ var sc = new float[25];
+ int sn = E.MidiEffectScope(trackId, index, sc);
+ int total = sn >= 25 ? (int)sc[24] : 0, have = Math.Min(12, total);
+ var last = new List<VelocityNote>(have);
+ for (int k = 12 - have; k < 12 && 2 * k + 1 < sn; k++) last.Add(new VelocityNote((int)MathF.Round(sc[2 * k] * 127), (int)MathF.Round(sc[2 * k + 1] * 127)));
+ int vlo = V(lo), vhi = V(hi);
+ return new VelocityState(VelModes[mode], MathF.Round(drive, 2), V(G(VFixed)), vlo, vhi, G(VRndOn) >= 0.5f,
+ (int)MathF.Round(Math.Clamp(G(VRnd), 0, 1) * 64), VelDirs[Math.Clamp((int)MathF.Round(G(VDir)), 0, 2)],
+ G(VView) >= 0.5f ? "S" : "L", curve, last.ToArray(), total);
+ });
+
+ [McpServerTool(Name = "set_velocity"), Description(
+ "Set a Nota Velocity's params by name; omit what you don't change. mode: curve | compand | fixed. drive 0.25..4 (1 = linear). "
+ + "fixedValue 1..127 (turns mode to fixed unless mode is given). outLow / outHigh 1..127 — the output range (kept low < high). "
+ + "randomAmount 0..64 velocity (turns Random on unless randomOn is given), randomOn, randomDirection both | up | down, view S|L.")]
+ public Task SetVelocity(int trackId, int index, string? mode = null, float? drive = null, int? fixedValue = null,
+ int? outLow = null, int? outHigh = null, bool? randomOn = null, float? randomAmount = null, string? randomDirection = null,
+ string? view = null) => Mutate(() =>
+ {
+ RequireVelocity(trackId, index);
+ float G(int p) => E.MidiEffectGetParam(trackId, index, p);
+ void S(int p, float v) => E.MidiEffectSetParam(trackId, index, p, v);
+ if (drive is { } d) S(VDrive, MathF.Round(Math.Clamp(d, 0.25f, 4f), 2));
+ if (fixedValue is { } fv) { S(VFixed, Math.Clamp(fv, 1, 127) / 127f); S(VMode, 2); }
+ if (mode is not null)
+ {
+ int m = Array.IndexOf(VelModes, mode.Trim().ToLowerInvariant());
+ if (m < 0) throw new ArgumentException($"Unknown mode '{mode}'. Use one of: curve, compand, fixed.");
+ S(VMode, m);
+ }
+ if (outLow is not null || outHigh is not null)
+ {
+ int lo = outLow ?? Math.Clamp((int)MathF.Round(G(VLo) * 127), 1, 127);
+ int hi = outHigh ?? Math.Clamp((int)MathF.Round(G(VHi) * 127), 1, 127);
+ lo = Math.Clamp(lo, 1, 126); hi = Math.Clamp(hi, 2, 127);
+ if (lo >= hi) { if (outHigh is null) hi = lo + 1; else lo = hi - 1; }
+ S(VLo, lo / 127f); S(VHi, hi / 127f);
+ }
+ if (randomAmount is { } r) { S(VRnd, MathF.Round(Math.Clamp(r, 0, 64)) / 64f); S(VRndOn, 1); }
+ if (randomOn is { } on) S(VRndOn, on ? 1 : 0);
+ if (randomDirection is not null)
+ {
+ int di = Array.IndexOf(VelDirs, randomDirection.Trim().ToLowerInvariant());
+ if (di < 0) throw new ArgumentException($"Unknown randomDirection '{randomDirection}'. Use one of: both, up, down.");
+ S(VDir, di);
+ }
+ if (view is not null) S(VView, view.Trim().Equals("S", StringComparison.OrdinalIgnoreCase) ? 1 : 0);
+ });
+
// ---- Nota Random (kind 5) — named access in musical units --------------------------------
// Param layout mirrors MidiRandom.h: Chance 0, Note Range 1, Vel Amt 2, Time Amt 3, Skip 4, Oct Amt 5,
// Dist 6, Rate 7, Stay In Scale 8, Locked 9, Seed 10, View 11, Lock Bar 12.
diff --git a/src/native/nota.engine/src/MidiVelocity.h b/src/native/nota.engine/src/MidiVelocity.h
index 3a1dd3fc..d9c4f326 100644
--- a/src/native/nota.engine/src/MidiVelocity.h
+++ b/src/native/nota.engine/src/MidiVelocity.h
@@ -1,13 +1,17 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Nota Velocity — a MIDI effect (midiKind 4), reworked to mockup 3b. Reshapes note-on
-// velocity through a transfer curve: Curve (drive / gamma — boost or attenuate soft notes),
-// Compand (expand/compress contrast around the middle) or Fixed (force a value). The result
-// is remapped into an output range and can be humanised with directional randomness. The
-// last note (in→out) and the last 12 output velocities are published for the editor.
+// Nota Velocity — a MIDI effect (midiKind 4), almanac rework (mockups 1a / 1b). Reshapes
+// note-on velocity through a transfer curve: Curve (x^(1/drive) — drive > 1 lifts soft notes,
+// < 1 pushes them down), Compand (the same around the middle — drive > 1 expands towards the
+// edges, < 1 squeezes towards the middle) or Fixed (one value). The result is remapped into
+// the Out range and can be humanised by Random (±0..64 velocity, Both / Up / Down), gated by
+// its own switch so the amount is kept while it is off. The output never leaves the range and
+// never reaches 0 (a velocity-0 note-on would be a note-off). The last note (in→out) and the
+// last 12 (in, out) pairs are published for the editor and MCP.
//
-// Param layout is APPEND-ONLY: 0..3 keep the original slots so old projects load unchanged.
+// Param layout is APPEND-ONLY: 0..6 keep the pre-almanac slots so old projects load unchanged
+// (Random On is then set from the old Random amount by the managed loader).
#pragma once
@@ -30,11 +34,18 @@ public:
PMode, // 0 Curve / 1 Compand / 2 Fixed
POutHi, // output range maximum
PRandomDir, // 0 Both / 1 Up / 2 Down
+ PRandomOn, // Random switch (the amount survives while it is off)
+ PView, // card size: 0 = L, 1 = S (editor state)
kNumParams
};
+ static constexpr float kDriveMin = 0.25f, kDriveMax = 4.0f; // 4^(2f-1), f = 0..1
+ static constexpr float kRandomSpan = 64.0f; // Random 1.0 = ±64 velocity
+ static constexpr int kHist = 12;
+
MidiVelocity() {
- p_[PDrive].store(1.0f); p_[PFixed].store(0.8f); p_[POutLo].store(0.0f); p_[PRandom].store(0.0f);
- p_[PMode].store(0.0f); p_[POutHi].store(1.0f); p_[PRandomDir].store(0.0f);
+ p_[PDrive].store(1.0f); p_[PFixed].store(100.0f / 127.0f); p_[POutLo].store(0.0f); p_[PRandom].store(0.25f);
+ p_[PMode].store(0.0f); p_[POutHi].store(1.0f); p_[PRandomDir].store(0.0f); p_[PRandomOn].store(0.0f);
+ p_[PView].store(0.0f);
}
int32_t midiKind() const override { return 4; }
@@ -44,29 +55,32 @@ public:
const char* paramName(int32_t i) const override {
switch (i) {
case PDrive: return "Drive"; case PFixed: return "Fixed"; case POutLo: return "Out Low"; case PRandom: return "Random";
- case PMode: return "Mode"; case POutHi: return "Out High"; case PRandomDir: return "Random Dir"; default: return "";
+ case PMode: return "Mode"; case POutHi: return "Out High"; case PRandomDir: return "Random Dir";
+ case PRandomOn: return "Random On"; case PView: return "View"; default: return "";
}
}
- float paramMin(int32_t) const override { return 0.0f; }
+ float paramMin(int32_t i) const override { return i == PDrive ? kDriveMin : 0.0f; }
float paramMax(int32_t i) const override {
- switch (i) { case PDrive: return 2.0f; case PMode: return 2.0f; case PRandomDir: return 2.0f; default: return 1.0f; }
+ switch (i) { case PDrive: return kDriveMax; case PMode: return 2.0f; case PRandomDir: return 2.0f; default: return 1.0f; }
}
float getParam(int32_t i) const override { return (i >= 0 && i < kNumParams) ? p_[i].load(std::memory_order_relaxed) : 0.0f; }
void setParam(int32_t i, float v) override { if (i >= 0 && i < kNumParams) p_[i].store(v, std::memory_order_relaxed); }
- // Live telemetry: last note in/out velocity (0..127), and the last 12 (in,out) pairs.
+ // Live telemetry: last note in/out velocity (1..127, -1 = none yet). The scope is the last
+ // 12 (in, out) pairs oldest → newest, 0..1 (unused slots 0, 0), then [24] = the number of
+ // notes shaped since the device was created (the editor spots a new note by it).
int32_t midiLastIn() const override { return lastIn_.load(std::memory_order_relaxed); }
int32_t midiLastOut() const override { return lastOut_.load(std::memory_order_relaxed); }
int32_t midiScope(float* out, int32_t maxN) const override {
if (!out || maxN <= 0) return 0;
- const int n = std::min(maxN, kHist * 2);
const uint32_t head = histHead_.load(std::memory_order_relaxed);
int w = 0;
- for (int k = 0; k < kHist && w + 1 < n; ++k) {
+ for (int k = 0; k < kHist && w + 1 < maxN; ++k) {
int idx = (int)((head + k) % kHist);
out[w++] = histIn_[idx];
out[w++] = histOut_[idx];
}
+ if (w < maxN && w == kHist * 2) out[w++] = (float)count_.load(std::memory_order_relaxed);
return w;
}
@@ -77,18 +91,23 @@ public:
return c;
}
- void reset() override { for (int i = 0; i < kHist; ++i) { histIn_[i] = 0; histOut_[i] = 0; } }
+ // Transport stop / loop wrap: the note history (the card's dots) stays — it is what was played.
+ void reset() override {}
void process(const MidiEv* in, int nIn, MidiEv* out, int& nOut, int maxOut,
int32_t, double, double, bool) override {
nOut = 0;
if (bypassed()) { for (int i = 0; i < nIn && nOut < maxOut; ++i) out[nOut++] = in[i]; return; }
- const float drive = std::clamp(p_[PDrive].load(std::memory_order_relaxed), 0.05f, 2.0f);
+ // A pre-almanac project may hold a drive below 0.25 — keep playing it as it was.
+ const float drive = std::clamp(p_[PDrive].load(std::memory_order_relaxed), 0.05f, kDriveMax);
const float fixed = std::clamp(p_[PFixed].load(std::memory_order_relaxed), 0.0f, 1.0f);
float lo = std::clamp(p_[POutLo].load(std::memory_order_relaxed), 0.0f, 1.0f);
float hi = std::clamp(p_[POutHi].load(std::memory_order_relaxed), 0.0f, 1.0f);
if (lo > hi) std::swap(lo, hi);
- const float rnd = std::clamp(p_[PRandom].load(std::memory_order_relaxed), 0.0f, 1.0f);
+ const float floorV = 1.0f / 127.0f; // never a velocity-0 note-on
+ lo = std::max(lo, floorV); hi = std::max(hi, floorV);
+ const float rnd = p_[PRandomOn].load(std::memory_order_relaxed) >= 0.5f
+ ? std::clamp(p_[PRandom].load(std::memory_order_relaxed), 0.0f, 1.0f) : 0.0f;
const int mode = std::clamp((int)std::lround(p_[PMode].load(std::memory_order_relaxed)), 0, 2);
const int dir = std::clamp((int)std::lround(p_[PRandomDir].load(std::memory_order_relaxed)), 0, 2);
@@ -100,16 +119,16 @@ public:
if (rnd > 0.0f) {
rng_ = rng_ * 1664525u + 1013904223u;
float u = (rng_ >> 8) / 16777216.0f; // 0..1
- float dev = rnd * 0.5f;
+ float dev = rnd * kRandomSpan / 127.0f;
float r = dir == 1 ? u * dev : dir == 2 ? -u * dev : (u * 2.0f - 1.0f) * dev;
v += r;
}
- v = std::clamp(v, lo, hi);
- const int outVel = (int)std::lround(v * 127.0f);
+ v = std::clamp(std::round(std::clamp(v, lo, hi) * 127.0f), 1.0f, 127.0f) / 127.0f; // whole MIDI steps
lastIn_.store((int)std::lround(std::clamp(e.vel, 0.0f, 1.0f) * 127.0f), std::memory_order_relaxed);
- lastOut_.store(outVel, std::memory_order_relaxed);
+ lastOut_.store((int)std::lround(v * 127.0f), std::memory_order_relaxed);
pushHist(std::clamp(e.vel, 0.0f, 1.0f), v);
- e.vel = std::clamp(v, 0.0f, 1.0f);
+ count_.fetch_add(1, std::memory_order_relaxed);
+ e.vel = v;
}
if (nOut < maxOut) out[nOut++] = e;
}
@@ -128,7 +147,6 @@ public:
}
private:
- static constexpr int kHist = 12;
// histHead_ = the next write slot, which is also the oldest entry — so scopeRead from
// head forward wraps chronologically oldest→newest.
void pushHist(float in, float outv) {
@@ -139,6 +157,7 @@ private:
float histIn_[kHist] = {}, histOut_[kHist] = {};
std::atomic<uint32_t> histHead_{0};
std::atomic<int32_t> lastIn_{-1}, lastOut_{-1};
+ std::atomic<uint32_t> count_{0};
uint32_t rng_ = 0x2545f491u;
std::atomic<float> p_[kNumParams];
};
diff --git a/src/native/nota.engine/src/Synth.h b/src/native/nota.engine/src/Synth.h
index fb20adb5..47518afe 100644
--- a/src/native/nota.engine/src/Synth.h
+++ b/src/native/nota.engine/src/Synth.h
@@ -12,6 +12,8 @@
// The first eight parameters keep their original index and meaning, so projects
// saved before the oscillator/voice sections existed load unchanged (setState
// reads whatever floats are present and leaves the rest at their defaults).
+// The last one, View, is editor state (the card's S / L size) — it persists and
+// clones with the patch but the managed layer keeps it out of presets/automation.
#pragma once
@@ -34,7 +36,9 @@ public:
enum Param {
Wave = 0, Attack, Decay, Sustain, Release, Cutoff, Resonance, Gain,
FilType, FilEnv, PulseWidth, Detune, Octave, Unison, Spread,
- Glide, VelAmp, Pan, VoiceMode, kNumParams
+ Glide, VelAmp, Pan, VoiceMode,
+ View, // editor state, not sound: the card size (0 = L, 1 = S)
+ kNumParams
};
Synth() {
@@ -58,6 +62,7 @@ public:
pn_[VelAmp].store(1.0f); // full velocity tracking — the pre-2026 behaviour
pn_[Pan].store(0.5f); // centre
pn_[VoiceMode].store(0.0f); // Poly 16
+ pn_[View].store(1.0f); // a new Synth opens as the mini (S) card
}
int32_t kind() const override { return 0; } // built-in Synth (M7-6) — project compat
@@ -71,14 +76,14 @@ public:
static const char* ids[] = {
"wave", "attack", "decay", "sustain", "release", "cutoff", "resonance", "gain",
"filtype", "filenv", "pulsewidth", "detune", "octave", "unison", "spread",
- "glide", "velamp", "pan", "voicemode" };
+ "glide", "velamp", "pan", "voicemode", "view" };
return (i >= 0 && i < kNumParams) ? std::string(ids[i]) : std::string{};
}
std::string pluginParamName(int32_t i) const override {
static const char* nm[] = {
"Wave", "Attack", "Decay", "Sustain", "Release", "Cutoff", "Resonance", "Gain",
"Filter Type", "Env →Cutoff", "Pulse Width", "Detune", "Octave", "Unison", "Spread",
- "Glide", "Vel →Vol", "Pan", "Voice Mode" };
+ "Glide", "Vel →Vol", "Pan", "Voice Mode", "View" };
return (i >= 0 && i < kNumParams) ? std::string(nm[i]) : std::string{};
}
float pluginParamGet(int32_t i) const override {
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index b60abe2f..eb6250ed 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -976,7 +976,7 @@ Console.WriteLine("-- Nota Synth --");
Check(se.DeviceName(t, -1) == "Nota Synth", $"instrument is Nota Synth (got '{se.DeviceName(t, -1)}')");
int pc = se.PluginParamCount(t, -1);
- Check(pc == 19, $"Nota Synth exposes 19 params (got {pc})");
+ Check(pc == 20, $"Nota Synth exposes 20 params (got {pc})");
int cut = -1; bool idsOk = true;
for (int i = 0; i < pc; i++)
{
@@ -1046,6 +1046,31 @@ Console.WriteLine("-- Nota Synth --");
&& Math.Abs(se.PluginParamGet(tl, -1, PIdx(tl, "voicemode")) - 0f) < 1e-4,
"params added since keep their defaults when an old state is loaded");
+ // The card size (S / L) is the last param, "view": a new Synth opens as S, the choice
+ // travels with the state blob (project save) and a duplicate, but presets neither save
+ // nor apply it.
+ {
+ int tv = se.AddInstrumentTrack();
+ int vi = InstrumentView.Index(se, tv);
+ Check(vi == pc - 1 && se.PluginParamId(tv, -1, vi) == "view", $"view is the last Synth param (index {vi})");
+ Check(InstrumentView.IsMini(se, tv) && Math.Abs(se.InstrumentParamDefault(tv, vi) - 1f) < 1e-4, "a new Synth defaults to the S card");
+ InstrumentView.SetMini(se, tv, false);
+ int tvs = se.AddInstrumentTrack();
+ se.SetPluginState(tvs, -1, se.GetPluginState(tv, -1));
+ Check(!InstrumentView.IsMini(se, tvs), "the L choice persists through the synth state");
+ int tvd = se.DuplicateTrack(tv);
+ Check(tvd > 0 && !InstrumentView.IsMini(se, tvd), "a duplicated Synth keeps its card size");
+ var doc = PresetService.Capture(se, tv, -1, "Mine");
+ Check(doc?.NamedParams is { } np && !np.ContainsKey("view") && np.ContainsKey("cutoff"), "a Synth user preset leaves the card size out");
+ var cat = new FactoryPresetCatalog();
+ var synthPresets = cat.All().Where(p => p.IsInstrument && p.BuiltinKind == 0).ToList();
+ Check(synthPresets.Count > 0 && cat.ApplyInPlace(se, synthPresets[0].Id, tv, -1).Length == 0 && !InstrumentView.IsMini(se, tv),
+ "applying a preset keeps the Synth's card size");
+ InstrumentView.SetMini(se, tv, true);
+ cat.ApplyInPlace(se, synthPresets[^1].Id, tv, -1);
+ Check(InstrumentView.IsMini(se, tv), "…in both sizes");
+ }
+
// Off / LP / HP / BP all pass signal, and each one sounds different from the others.
int tf = se.AddInstrumentTrack();
se.AddMidiClip(tf, 0.0, 4.0);
@@ -6879,51 +6904,158 @@ Console.WriteLine("-- Nota Length --");
}
}
-// ===================== Nota Velocity (MIDI kind 4) rework =====================
+// ===================== Nota Velocity (MIDI kind 4) — almanac rework =====================
Console.WriteLine("-- Nota Velocity --");
{
using var e = new NotaEngine();
e.SetBpm(120); e.SetTimeSignature(4, 4);
int t = e.AddInstrumentTrack();
int m = e.AddMidiEffect(t, 4);
- Check(m == 0 && e.MidiEffectName(t, 0) == "Nota Velocity", "add Nota Velocity");
+ Check(m == 0 && e.MidiEffectName(t, 0) == "Nota Velocity" && e.MidiEffectKind(t, 0) == 4, "add Nota Velocity");
int pc = e.MidiEffectParamCount(t, 0);
- Check(pc == 7, $"Nota Velocity exposes 7 params (got {pc})");
- var pn = new System.Collections.Generic.HashSet<string>();
- for (int i = 0; i < pc; i++) pn.Add(e.MidiEffectParamName(t, 0, i));
- Check(pn.Contains("Drive") && pn.Contains("Mode") && pn.Contains("Out Low") && pn.Contains("Out High")
- && pn.Contains("Random Dir") && pn.Contains("Fixed") && pn.Contains("Random"), "mockup-3b params present");
+ Check(pc == 9, $"Nota Velocity exposes 9 params (got {pc})");
+ string[] expect = { "Drive", "Fixed", "Out Low", "Random", "Mode", "Out High", "Random Dir", "Random On", "View" };
+ bool layout = true; for (int i = 0; i < expect.Length; i++) layout &= e.MidiEffectParamName(t, 0, i) == expect[i];
+ Check(layout, "param layout is append-only (… Random Dir, then Random On / View)");
+ Check(e.MidiEffectParamMin(t, 0, 0) == 0.25f && e.MidiEffectParamMax(t, 0, 0) == 4f, "Drive spans 0.25..4");
+ Check(GetByName(e, t, 0, "Drive") == 1f && GetByName(e, t, 0, "Random On") == 0f && Math.Abs(GetByName(e, t, 0, "Random") - 0.25f) < 1e-6,
+ "defaults: linear, Random off (±16 ready)");
- // Fixed mode forces velocity: play a soft note, the last-in/out telemetry reports the
- // forced output and it differs from the input.
e.AddMidiClip(t, 0.0, 4.0);
- e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 1.0, 0.3f) }); // vel ~38
- SetByName(e, t, 0, "Mode", 2f); SetByName(e, t, 0, "Fixed", 0.8f);
- var b = new float[12000 * 2]; e.Seek(0); e.Play(); e.RenderOffline(b, 12000); e.StopTransport();
- int li = e.MidiEffectLastIn(t, 0), lo = e.MidiEffectLastOut(t, 0);
- Check(li is > 30 and < 46 && lo is > 95 and < 108, $"Fixed mode forces velocity (in {li} → out {lo})");
-
- // Scope publishes 12 in/out pairs for the histogram/curve.
- var scope = new float[24];
+ var scope = new float[25];
+ // One note through the device → (last in, last out) from the telemetry.
+ (int In, int Out) Play(float vel)
+ {
+ e.StopTransport();
+ e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 0.5, vel) });
+ var buf = new float[4096 * 2]; e.Seek(0); e.Play(); e.RenderOffline(buf, 4096); e.StopTransport();
+ return (e.MidiEffectLastIn(t, 0), e.MidiEffectLastOut(t, 0));
+ }
+ int Expect(double inVel, int mode, double drive, double fixedN, double lo, double hi)
+ {
+ double n = inVel, shaped = mode == 2 ? fixedN : mode == 1 ? 0.5 + Math.Sign(2 * n - 1) * Math.Pow(Math.Abs(2 * n - 1), 1 / drive) * 0.5 : Math.Pow(n, 1 / drive);
+ return (int)Math.Round((lo + shaped * (hi - lo)) * 127);
+ }
+
+ var r = Play(64f / 127f);
+ Check(r.In == 64 && r.Out == 64, $"linear by default ({r.In} → {r.Out})");
+ SetByName(e, t, 0, "Drive", 2f);
+ r = Play(32f / 127f); Check(r.Out == Expect(32 / 127.0, 0, 2, 0, 1 / 127.0, 1), $"Curve drive 2 lifts a soft note ({r.In} → {r.Out})");
+ SetByName(e, t, 0, "Drive", 4f);
+ r = Play(16f / 127f); Check(r.Out == Expect(16 / 127.0, 0, 4, 0, 1 / 127.0, 1) && r.Out > 70, $"Curve drive 4 (the new top) ({r.In} → {r.Out})");
+ SetByName(e, t, 0, "Mode", 1f); SetByName(e, t, 0, "Drive", 0.5f);
+ r = Play(100f / 127f); Check(r.Out == Expect(100 / 127.0, 1, 0.5, 0, 1 / 127.0, 1) && r.Out < 100, $"Compand 0.5 squeezes to the middle ({r.In} → {r.Out})");
+ SetByName(e, t, 0, "Mode", 2f); SetByName(e, t, 0, "Fixed", 100f / 127f);
+ r = Play(0.3f); Check(r.Out == 100, $"Fixed forces 100 ({r.In} → {r.Out})");
+ SetByName(e, t, 0, "Out Low", 20f / 127f); SetByName(e, t, 0, "Out High", 60f / 127f);
+ r = Play(0.3f); Check(r.Out == Expect(0.3, 2, 1, 100 / 127.0, 20 / 127.0, 60 / 127.0), $"Fixed goes through the Out range ({r.Out})");
+ SetByName(e, t, 0, "Mode", 0f); SetByName(e, t, 0, "Drive", 1f); SetByName(e, t, 0, "Out Low", 0f); SetByName(e, t, 0, "Out High", 0f);
+ r = Play(0.9f); Check(r.Out == 1, $"a zero Out range still plays velocity 1, never a note-off ({r.Out})");
+ SetByName(e, t, 0, "Out High", 1f);
+
+ // Random: off by default even with an amount; on, it stays within ±amount and the direction holds.
+ var outs = new System.Collections.Generic.List<int>();
+ for (int k = 0; k < 6; k++) outs.Add(Play(64f / 127f).Out);
+ Check(outs.All(x => x == 64), "Random off: the amount is kept but does nothing");
+ SetByName(e, t, 0, "Random On", 1f); SetByName(e, t, 0, "Random", 0.5f); // ±32
+ outs.Clear(); for (int k = 0; k < 12; k++) outs.Add(Play(64f / 127f).Out);
+ Check(outs.All(x => x >= 32 && x <= 96) && outs.Distinct().Count() > 3, $"Random ±32 spreads both ways ({string.Join(" ", outs)})");
+ SetByName(e, t, 0, "Random Dir", 1f);
+ outs.Clear(); for (int k = 0; k < 8; k++) outs.Add(Play(64f / 127f).Out);
+ Check(outs.All(x => x >= 64 && x <= 96), $"Random up only adds ({string.Join(" ", outs)})");
+ SetByName(e, t, 0, "Random Dir", 2f);
+ outs.Clear(); for (int k = 0; k < 8; k++) outs.Add(Play(64f / 127f).Out);
+ Check(outs.All(x => x >= 32 && x <= 64), $"Random down only subtracts ({string.Join(" ", outs)})");
+ SetByName(e, t, 0, "Random Dir", 1f); SetByName(e, t, 0, "Random", 1f); SetByName(e, t, 0, "Out High", 70f / 127f); // base ≈ 36, up to +64
+ outs.Clear(); for (int k = 0; k < 16; k++) outs.Add(Play(64f / 127f).Out);
+ Check(outs.All(x => x >= 35 && x <= 70) && outs.Contains(70), $"Random never leaves the Out range ({string.Join(" ", outs)})");
+ SetByName(e, t, 0, "Out High", 1f); SetByName(e, t, 0, "Random Dir", 0f); SetByName(e, t, 0, "Random On", 0f);
+
+ // Telemetry: 12 (in, out) pairs oldest → newest + the note count; the history survives a stop.
int sn = e.MidiEffectScope(t, 0, scope);
- bool sok = sn == 24; for (int i = 0; i < sn; i++) if (!float.IsFinite(scope[i]) || scope[i] < 0 || scope[i] > 1.001f) sok = false;
- Check(sok, $"scope publishes 12 in/out pairs (n={sn})");
+ bool sok = sn == 25; for (int i = 0; i < 24; i++) if (!float.IsFinite(scope[i]) || scope[i] < 0 || scope[i] > 1.001f) sok = false;
+ Check(sok && scope[24] >= 12, $"scope: 12 in/out pairs + the note count (n={sn}, count {scope[24]})");
+ Check(Math.Abs(scope[22] * 127 - e.MidiEffectLastIn(t, 0)) < 0.6 && Math.Abs(scope[23] * 127 - e.MidiEffectLastOut(t, 0)) < 0.6, "the newest pair is the last note");
- // Curve + Compand + Random render finite.
+ // Every mode renders finite + audible.
void Fin(string tag, Action cfg)
{
cfg();
+ e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 1.0, 0.5f) });
var buf = new float[12000 * 2]; e.Seek(0); e.Play(); e.RenderOffline(buf, 12000); e.StopTransport();
- bool fin = true; foreach (var s in buf) if (!float.IsFinite(s) || Math.Abs(s) > 8f) { fin = false; break; }
+ bool fin = true; foreach (var x in buf) if (!float.IsFinite(x) || Math.Abs(x) > 8f) { fin = false; break; }
Check(fin && Rms(buf, 12000) > 0.0005f, $"{tag} renders finite + audible");
}
Fin("Curve + drive", () => { SetByName(e, t, 0, "Mode", 0f); SetByName(e, t, 0, "Drive", 1.6f); });
Fin("Compand + range", () => { SetByName(e, t, 0, "Mode", 1f); SetByName(e, t, 0, "Out Low", 0.2f); SetByName(e, t, 0, "Out High", 0.9f); });
- Fin("Random up", () => { SetByName(e, t, 0, "Random", 0.4f); SetByName(e, t, 0, "Random Dir", 1f); });
+ Fin("Random up", () => { SetByName(e, t, 0, "Random On", 1f); SetByName(e, t, 0, "Random", 0.4f); SetByName(e, t, 0, "Random Dir", 1f); });
- SetByName(e, t, 0, "Drive", 0.7f);
+ SetByName(e, t, 0, "Drive", 0.7f); SetByName(e, t, 0, "View", 1f);
int t2 = e.DuplicateTrack(t);
- Check(t2 > 0 && Math.Abs(GetByName(e, t2, 0, "Drive") - 0.7f) < 1e-3, "duplicate track clones Velocity params");
+ Check(t2 > 0 && Math.Abs(GetByName(e, t2, 0, "Drive") - 0.7f) < 1e-3 && GetByName(e, t2, 0, "Random On") == 1f && GetByName(e, t2, 0, "View") == 1f,
+ "duplicate track clones Velocity params");
+
+ // A project from before the Random switch (7 params): a Random amount stays live, none stays off.
+ foreach (var (amt, want) in new[] { (0.3f, 1f), (0f, 0f) })
+ {
+ var w = new System.Collections.Generic.List<string>();
+ var doc = ProjectService.Capture(e, new TransportState(120, 1, false, false), w);
+ var md = doc.Tracks.First(x => x.MidiEffects.Count > 0 && x.MidiEffects[0].Kind == 4).MidiEffects[0];
+ md.Params = new float[] { 1.4f, 0.8f, 0f, amt, 0f, 1f, 0f };
+ using var e2 = new NotaEngine();
+ ProjectService.Apply(doc, e2, Path.GetTempPath());
+ int vt = -1;
+ for (int i = 0; e2.TryGetTrackInfo(i, out var ti); i++) if (e2.TrackMidiEffectCount(ti.Id) > 0 && e2.MidiEffectKind(ti.Id, 0) == 4) { vt = ti.Id; break; }
+ Check(vt > 0 && GetByName(e2, vt, 0, "Random On") == want && Math.Abs(GetByName(e2, vt, 0, "Drive") - 1.4f) < 1e-4,
+ $"legacy Velocity project (Random {amt}): Random On = {want}");
+ }
+
+ // Factory presets: 25+, every name valid, each applies in place and renders.
+ {
+ var cat = new FactoryPresetCatalog();
+ var mine = cat.All().Where(p => p.IsMidiEffect && p.BuiltinKind == 4).ToList();
+ Check(mine.Count >= 25, $"Nota Velocity ships 25+ factory presets (got {mine.Count})");
+ var names = new System.Collections.Generic.HashSet<string>();
+ for (int i = 0; i < pc; i++) names.Add(e.MidiEffectParamName(t, 0, i));
+ var bad = mine.SelectMany(p => cat.Document(p.Id)!.NamedParams!.Keys.Where(k => !names.Contains(k)).Select(k => $"{p.DisplayName}:{k}")).ToList();
+ Check(bad.Count == 0, $"every Velocity preset param name exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");
+ var off = new System.Collections.Generic.List<string>();
+ e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 1.0, 0.9f), new NotaNote(64, 1.0, 1.0, 0.4f) });
+ foreach (var p in mine)
+ {
+ if (cat.ApplyInPlace(e, p.Id, t, 0).Length != 0) { off.Add(p.DisplayName + " (apply)"); continue; }
+ var pb = new float[40000 * 2]; e.Seek(0); e.Play(); e.RenderOffline(pb, 40000); e.StopTransport();
+ bool ok = true; foreach (var x in pb) if (!float.IsFinite(x) || Math.Abs(x) > 8f) { ok = false; break; }
+ if (!ok || Rms(pb, 40000) < 0.0005f) off.Add(p.DisplayName);
+ }
+ Check(off.Count == 0, $"every Velocity preset applies and renders{(off.Count > 0 ? " — off: " + string.Join(", ", off) : "")}");
+ Check(GetByName(e, t, 0, "View") == 1f, "presets leave the card size (View) alone");
+ var hum = mine.First(p => p.DisplayName == "Humanize");
+ cat.ApplyInPlace(e, hum.Id, t, 0);
+ Check(GetByName(e, t, 0, "Random On") == 1f && Math.Abs(GetByName(e, t, 0, "Random") * 64 - 16) < 0.01, "Humanize: Random ±16 on");
+ }
+
+ // MCP: named access in musical units.
+ {
+ var mcp = new Nota.Mcp.Tools.MidiFxTools(e, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());
+ mcp.SetVelocity(t, 0, mode: "compand", drive: 0.5f, outLow: 30, outHigh: 110, randomAmount: 10, randomDirection: "up", view: "L").GetAwaiter().GetResult();
+ var st = mcp.GetVelocity(t, 0).GetAwaiter().GetResult();
+ Check(st.Mode == "compand" && Math.Abs(st.Drive - 0.5f) < 1e-3 && st.OutLow == 30 && st.OutHigh == 110 && st.RandomOn && st.RandomAmount == 10
+ && st.RandomDirection == "up" && st.View == "L", $"MCP set/get_velocity round-trip ({st.Mode} {st.Drive} {st.OutLow}–{st.OutHigh} {st.RandomAmount} {st.RandomDirection})");
+ Check(st.Curve.Length == 9 && st.Curve[0] >= 30 && st.Curve[^1] <= 110 && st.Curve[4] == 70, $"MCP curve sits in the Out range ({string.Join(" ", st.Curve)})");
+ mcp.SetVelocity(t, 0, fixedValue: 77, randomOn: false).GetAwaiter().GetResult();
+ st = mcp.GetVelocity(t, 0).GetAwaiter().GetResult();
+ Check(st.Mode == "fixed" && st.FixedValue == 77 && !st.RandomOn, "MCP fixedValue switches to fixed mode");
+ mcp.SetVelocity(t, 0, outLow: 120, outHigh: 100).GetAwaiter().GetResult();
+ st = mcp.GetVelocity(t, 0).GetAwaiter().GetResult();
+ Check(st.OutLow < st.OutHigh, $"MCP keeps outLow below outHigh ({st.OutLow}–{st.OutHigh})");
+ mcp.SetVelocity(t, 0, mode: "curve", drive: 1, outLow: 1, outHigh: 127).GetAwaiter().GetResult();
+ Play(0.5f);
+ st = mcp.GetVelocity(t, 0).GetAwaiter().GetResult();
+ Check(st.LastNotes.Length > 0 && st.LastNotes[^1].In == 64 && st.LastNotes[^1].Out == 64 && st.NotesShaped > 0, "MCP reports the last notes in → out");
+ bool threw = false; try { mcp.SetVelocity(t, 0, mode: "loud").GetAwaiter().GetResult(); } catch (ArgumentException) { threw = true; }
+ Check(threw, "MCP rejects an unknown mode");
+ }
}
// ===================== Nota Random (MIDI kind 5) rework =====================