Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
Redesign of Length, Random, Scale
Egor Khindikaynenfa40c6bdb637
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2bfc6f27..0f4b99d1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -60,8 +60,47 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.- Nota Chord has 34 presets. The automation menu lists its settings, and each shift'ssemitones, switch and velocity are under Shifts. MCP gets new tools for it: `get_chord`,`set_chord` and `set_chord_shift`.+- Nota Length has a new look in the same two sizes, a full card and a small 260-pixel one.+ The GATE window now shows a bar of five notes and what happens to each: the note played in+ is outlined, the note that comes out is filled, and a band shows how far Random can move+ it. A playhead runs across the bar, and Random picks new lengths on every pass.+- Nota Length's Sync mode has eight lengths, from 1/32 to a whole bar, plus dotted 1/8 and+ triplet 1/4. Vel → Len and Key → Len now go both ways: plus makes loud (or low) notes+ longer, minus makes them shorter. Legato now holds each note until the next one starts.+ Clip length limit stops a note at the end of the bar. Projects and presets from older+ versions load with the same lengths as before.+- Nota Length has 32 presets. The automation menu lists its settings, and MCP gets new tools+ for it: `get_length` and `set_length`.+- Nota Random has a new look in the same two sizes, a full card and a small 260-pixel one.+ The OUTPUT window shows a bar of eight notes: the note played in is dashed, the note that+ comes out is filled (brighter when louder), and a skipped note gets a ×. A playhead runs+ across the bar, and every bar is a new roll. The DICE panel draws the chosen distribution+ from the same dice the device uses.+- Nota Random's Lock now holds the roll you see on screen and repeats it every bar; Reroll+ moves to the next seed. Stay in scale keeps notes in C major. Timing now delays notes by+ up to 100 ms.+- Nota Random has 32 presets. The automation menu lists its settings, and MCP gets new tools+ for it: `get_random` and `set_random`.+- Nota Scale has a new look in the same two sizes, a full card and a small 260-pixel one.+ The NOTE MAP shows C to B as keys: scale notes are filled, the root is outlined, and every+ other note shows where it goes. Click a note to add it or take it out. The note you play+ lights up, along with the note it turns into, and fades out when you let go.+- Nota Scale's Learn is now a mode: while it's on, the notes you play pass through and+ become a new Custom scale. Follow key now finds the key that best fits what you play.+ Clear leaves only the root.+- 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`.### Fixed+- Nota Scale no longer leaves notes hanging when you change the scale, root or fold while a+ key is held, or when two held keys land on the same note.+- Nota Length's Gate % below 100 % now shortens notes from a clip. Before, a note always+ lasted at least as long as it was held.+- Nota Length no longer leaves notes hanging when you bypass it while a note is sounding.+- Nota Random's Timing now really moves notes. Before, a shift longer than a few milliseconds+ was cut short, so most notes played on time.+- Nota Random no longer leaves a transposed note hanging when you bypass it while it sounds.- Nota Chord no longer leaves notes hanging when you change its shifts while a key is held,or when two held keys share a note.diff --git a/FEATURES.md b/FEATURES.mdindex 7562ffcd..f453cecc 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -529,14 +529,29 @@ and user presets, automation, persistence and cloning.(Velocity/Length/Chance/Ratchet/Transpose) plus step mute; Free/Sync (1/1…1/32), Gate,Swing, Vel Amt, Retrig Off/Note/Beat, Transpose, Steps 1–16, Hold, Restart. 30 presets,full automation, MCP tools (`get_arp` / `set_arp` / `set_arp_lane` / `set_arp_step` / `restart_arp`).-- **Nota Scale** — snap to a scale: Root, Major/Minor/Dorian/Phryg/Penta/Custom, Fold- (Nearest/Down/Up), NOTE MAP, Range, Follow Key, Learn/Clear.-- **Nota Length** (formerly Note Length) — note lengths: Sync/ms/Gate %, Vel→Len, Key→Len,- Random, Legato, clip length limit; a GATE visualiser.+- **Nota Scale** — snaps notes into a scale, in two sizes (L 700 / S 260, S·L toggle; one+ preset list for both): Root, Major/Minor/Dorian/Phryg/Penta/Custom (older scales such as+ Lydian or Harmonic minor still load and show by name), Fold Nearest/Down/Up, Transpose, a+ clickable NOTE MAP (C → B as key cells: scale notes filled, root outlined, the rest showing+ where they fold; the note playing lights up with its target and fades out), last IN → OUT,+ Range (outside passes through), Follow key (the root follows what you play), Learn (a mode+ that builds a Custom scale from the notes you play) and Clear. Held notes release correctly+ when the scale changes. 35 presets, full automation, MCP tools (`get_scale` / `set_scale` /+ `set_scale_note`).+- **Nota Length** (formerly Note Length) — forces note lengths: Sync (1/32 … 1/1, 1/8., 1/4T) /+ ms / Gate % (of the held length; clip notes can also shorten), start from note-on or+ note-off, bipolar Vel → Len and Key → Len, Random, Legato (to the next note), Clip length+ 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, OutRange, Random Dir, and a Last 12 histogram.-- **Nota Random** — randomization: Chance, Gauss/Even/Walk, Lock seed / Re-roll,- Note/Velocity/Timing/Skip/Octave amounts, Distribution, Rate, Stay in scale.+- **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).+ Two sizes (L 700 / S 260) with an animated OUTPUT window (one bar of eight notes, input dashed,+ output filled by velocity, × for skipped) and a DICE histogram drawn from the same generator.+ 32 presets, full automation, MCP tools (`get_random` / `set_random`).- **Nota Chord** — chord generator in two sizes (L 700 / S 260, S·L toggle; one preset listfor both): TYPE Maj7/Min7/Sus4/5th/Custom, six switchable shifts (±12 st ruler + intervalname + velocity offset), Strum 0–100 ms (low → high), Spread (every other / all shifts up andiff --git a/src/managed/Nota.App/ArrangementView.Automation.cs b/src/managed/Nota.App/ArrangementView.Automation.csindex 3f5a59b0..00a762a0 100644--- a/src/managed/Nota.App/ArrangementView.Automation.cs+++ b/src/managed/Nota.App/ArrangementView.Automation.cs@@ -492,6 +492,54 @@ public sealed partial class ArrangementViewmMenu.Items.Add(new Separator());mMenu.Items.Add(shifts);}+ else if (e.MidiEffectKind(t.Id, m) == 2 && mpc > ScaleMidiBody.PView)+ {+ // Nota Scale: the key, fold and range by name, then Notes ▸ each scale degree of+ // the Custom mask. View (the card size) is editor state.+ (int p, string label)[] ps =+ {+ (ScaleMidiBody.PRoot, "Root"), (ScaleMidiBody.PScale, "Scale"), (ScaleMidiBody.PFold, "Fold"),+ (ScaleMidiBody.PTranspose, "Transpose"), (ScaleMidiBody.PRangeLo, "Range Low"), (ScaleMidiBody.PRangeHi, "Range High"),+ (ScaleMidiBody.PFollowKey, "Follow Key"), (ScaleMidiBody.PLearn, "Learn"),+ };+ foreach (var (p, label) in ps) mMenu.Items.Add(MLeaf(m, p, label));+ var notes = new MenuItem { Header = "Custom Notes" };+ string[] degrees = { "Root", "♭2", "2", "♭3", "3", "4", "♭5", "5", "♭6", "6", "♭7", "7" };+ for (int d = 0; d < 12; d++) notes.Items.Add(MLeaf(m, ScaleMidiBody.PMask0 + d, degrees[d]));+ mMenu.Items.Add(new Separator());+ mMenu.Items.Add(notes);+ }+ else if (e.MidiEffectKind(t.Id, m) == 3 && mpc > LengthMidiBody.PView)+ {+ // Nota Length: its sound params by name. Rate / Gate (pre-Division sync) and+ // View (the card size) are not offered.+ (int p, string label)[] ps =+ {+ (LengthMidiBody.PMode, "Mode"), (LengthMidiBody.PDivision, "Division (Sync)"), (LengthMidiBody.PMs, "Length (ms)"),+ (LengthMidiBody.PPercent, "Length (Gate %)"), (LengthMidiBody.PTrigger, "Start From"),+ (LengthMidiBody.PVelToLen, "Vel → Len"), (LengthMidiBody.PKeyToLen, "Key → Len"), (LengthMidiBody.PRandom, "Random"),+ (LengthMidiBody.PLegato, "Legato"), (LengthMidiBody.PClipLimit, "Clip Length Limit"),+ };+ foreach (var (p, label) in ps) 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+ // the Lock button) are not offered.+ (int p, string label)[] ps =+ {+ (RandomModel.PNoteRange, "Note"), (RandomModel.PVelAmt, "Velocity"), (RandomModel.PTimeAmt, "Timing"),+ (RandomModel.PSkip, "Skip"), (RandomModel.POctAmt, "Octave"),+ };+ foreach (var (p, label) in ps) mMenu.Items.Add(MLeaf(m, p, label));+ mMenu.Items.Add(new Separator());+ (int p, string label)[] dice =+ {+ (RandomModel.PChance, "Chance"), (RandomModel.PDist, "Distribution"), (RandomModel.PRate, "Rate"),+ (RandomModel.PSeed, "Seed"), (RandomModel.PLocked, "Lock"), (RandomModel.PStayInScale, "Stay In Scale"),+ };+ foreach (var (p, label) in dice) mMenu.Items.Add(MLeaf(m, p, label));+ }else{int shown = Math.Min(mpc, 16); // globals (+ a few lanes); per-step lanes are edited in the griddiff --git a/src/managed/Nota.App/Controls/DistributionViz.cs b/src/managed/Nota.App/Controls/DistributionViz.csdeleted file mode 100644index 51a1de86..00000000--- a/src/managed/Nota.App/Controls/DistributionViz.cs+++ /dev/null@@ -1,50 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.-//-// Nota Random distribution shape (mockup 3b): the probability shape of the random offset —-// Gauss (bell), Even (flat) or Walk (drift / triangular) — drawn as teal bars over a −max …-// centre … +max span, so the choice is visible.--using System;-using Avalonia;-using Avalonia.Controls;-using Avalonia.Media;--namespace Nota.App;--internal sealed class DistributionViz : Control-{- private static readonly IBrush Well = NotaPalette.BgSunken;- private static readonly IBrush BorderIn = NotaPalette.GraphBorder;- private static Color Teal => NotaPalette.Teal.Color;- private const int N = 16;-- private int _dist;-- public DistributionViz() { MinHeight = 40; }- public void Set(int dist) { _dist = Math.Clamp(dist, 0, 2); InvalidateVisual(); }-- public override void Render(DrawingContext ctx)- {- double w = Bounds.Width, h = Bounds.Height;- if (w <= 0 || h <= 0) return;- NotaGraph.Window(ctx, new Rect(0, 0, w, h));- double padX = 6, padY = 5;- double x0 = padX, x1 = w - padX, top = padY, bot = h - padY;- double bw = (x1 - x0) / N;- for (int k = 0; k < N; k++)- {- double t = (k + 0.5) / N; // 0..1 across the span- double c = (t - 0.5) * 2; // -1..1 (centre = 0)- double hh = _dist switch- {- 1 => 1.0, // Even- 2 => 1.0 - Math.Abs(c), // Walk (triangular drift)- _ => Math.Exp(-(c * c) * 4.0), // Gauss- };- double bh = Math.Max(1, hh * (bot - top));- var rect = new Rect(x0 + k * bw + 0.5, bot - bh, Math.Max(1, bw - 1.4), bh);- ctx.DrawRectangle(NotaPalette.Teal, null, rect, NotaRadius.BarValue, NotaRadius.BarValue);- }- }-}diff --git a/src/managed/Nota.App/Controls/LengthGateViz.cs b/src/managed/Nota.App/Controls/LengthGateViz.csindex 2ead5a62..71f5adc3 100644--- a/src/managed/Nota.App/Controls/LengthGateViz.cs+++ b/src/managed/Nota.App/Controls/LengthGateViz.cs@@ -1,11 +1,18 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Nota Length gate viz (mockup 3b): the forced note length drawn as a bar on a 0…2 s time-// axis, so "620 ms" is a length you can see. Two bars show the min/max the modifiers-// (velocity · key · random) spread the length across; when no modifier is active they match.+// Nota Length GATE window (almanac mockups 1a / 1b): one bar of five demo notes of different+// pitch and velocity, and what the device does to each. Per row: the input note as an+// outline, the output note as a brass fill, and a dark band behind it — the range Random+// spreads that note's length over. The window runs 1¼ bars; the part after the bar line is+// shaded (Clip length limit cuts there). A playhead sweeps the bar; the note under it lights+// Brass Light, and Random re-rolls each pass. The full view adds note labels, the output+// length tags and a ms ruler; the mini view is the window alone.+//+// The model mirrors MidiNoteLength::len/schedule so the picture is what the device plays.using System;+using System.Collections.Generic;using System.Globalization;using Avalonia;using Avalonia.Controls;@@ -16,61 +23,160 @@ namespace Nota.App;internal sealed class LengthGateViz : Control{private static readonly IBrush Well = NotaPalette.BgSunken;- private static readonly IBrush BorderIn = NotaPalette.GraphBorder;- private static readonly IBrush Track = NotaPalette.BgSunken;- private static readonly IBrush Amber = NotaPalette.Accent;- private static readonly IBrush AmberDim = NotaPalette.Wash(NotaPalette.Accent, 0x88);- private static readonly IBrush Muted = NotaPalette.TextTertiary;+ private static readonly IBrush WellEdge = NotaPalette.GraphBorder;+ private static readonly IBrush BeatLine = NotaPalette.GraphBorder;+ private static readonly IBrush HalfLine = NotaPalette.SurfaceCard;+ private static readonly IBrush PastBar = NotaPalette.Wash(NotaPalette.SurfaceAbyss, 0xA0); // like the piano roll past the clip end+ private static readonly IBrush Band = NotaPalette.Ink("#2A2317");+ private static readonly IBrush Fill = NotaPalette.Ink("#B8862E");+ private static readonly IBrush FillLit = NotaPalette.AccentBright;+ private static readonly IBrush FillOff = NotaPalette.BorderStrong;+ private static readonly IBrush Outline = NotaPalette.TextMuted;+ private static readonly IBrush Head = NotaPalette.Wash(NotaPalette.AccentBright, 0xB3);+ private static readonly IBrush Label = NotaPalette.TextSecondary;+ private static readonly IBrush VelInk = NotaPalette.TextDisabled;+ private static readonly IBrush TagInk = NotaPalette.TextMuted;private static readonly IBrush Axis = NotaPalette.TextAxis;- private static readonly IBrush Sub = NotaPalette.TextSecondary;- private static readonly Typeface Mono = NotaFonts.Mono;- private const double FullMs = 2000.0;- private double _minMs, _maxMs, _bpm = 120;+ public const double Bar = 4.0, Window = 5.0; // beats: one 4/4 bar, the window 1¼ bars++ /// <summary>The demo phrase, in beats (at 120 BPM: 0 / 500 / 750 / 1250 / 1500 ms).</summary>+ internal static readonly (double T, double Len, int Key, int Vel)[] Input =+ {+ (0.0, 0.76, 48, 112), (1.0, 0.32, 55, 64), (1.5, 1.04, 60, 96), (2.5, 0.40, 67, 44), (3.0, 0.72, 72, 124),+ };++ /// <summary>One note of the model, in beats: where the forced note starts, its output+ /// length and the Random range [lo, hi].</summary>+ internal readonly record struct Note(double Start, double Out, double Lo, double Hi);++ // Param indices — mirror MidiNoteLength.h.+ private const int PGate = 1, PMode = 2, PMs = 3, PPercent = 4, PTrigger = 5, PVel = 6, PKey = 7, PRandom = 8, PLegato = 9, PClip = 10, PDivision = 11;+ internal static readonly double[] DivBeats = { 0.125, 0.25, 0.5, 1.0, 2.0, 4.0, 0.75, 2.0 / 3.0 };- public LengthGateViz() { MinHeight = 60; }+ private static double Hash(int i, int cycle)+ {+ double x = Math.Sin((i + 1) * 12.9898 + cycle * 78.233) * 43758.5453;+ return (x - Math.Floor(x)) * 2 - 1;+ }+ private static double BarEnd(double beat) => (Math.Floor(beat / Bar + 1e-9) + 1) * Bar;- public void Set(double minMs, double maxMs, double bpm)+ /// <summary>The five notes as the device would play them at this tempo; <paramref name="cycle"/>+ /// seeds Random (a new roll per bar).</summary>+ internal static Note[] Compute(Func<int, float> g, double bpm, int cycle){- _minMs = minMs; _maxMs = maxMs; _bpm = bpm > 0 ? bpm : 120;+ int mode = Math.Clamp((int)Math.Round(g(PMode)), 0, 2);+ bool onOff = g(PTrigger) >= 0.5f, legato = g(PLegato) >= 0.5f, clip = g(PClip) >= 0.5f;+ double vel = Math.Clamp(g(PVel), -1, 1), key = Math.Clamp(g(PKey), -1, 1), rnd = Math.Clamp(g(PRandom), 0, 1);+ double beatsPerMs = (bpm > 0 ? bpm : 120) / 60000.0;+ double Start(int i) => onOff ? Input[i].T + Input[i].Len : Input[i].T;+ var notes = new Note[Input.Length];+ for (int i = 0; i < Input.Length; i++)+ {+ var n = Input[i];+ double L = mode switch+ {+ 1 => Math.Clamp(g(PMs), 1, 2000) * beatsPerMs,+ 2 => n.Len * Math.Clamp(g(PPercent), 1, 200) / 100.0,+ _ => DivBeats[Math.Clamp((int)Math.Round(g(PDivision)), 0, DivBeats.Length - 1)] * Math.Clamp(g(PGate), 0.05, 2.0),+ };+ L *= Math.Max(0.05, 1 + vel * (n.Vel - 64) / 64.0);+ L *= Math.Max(0.05, 1 - key * (n.Key - 60) / 24.0);+ double s = Start(i);+ double lo = L * (1 - rnd), hi = L * (1 + rnd), o = L * (1 + rnd * Hash(i, cycle));+ if (legato)+ {+ // Until the next note starts, at most to the bar line.+ double next = double.PositiveInfinity;+ for (int j = 0; j < Input.Length; j++) if (j != i && Start(j) > s && Start(j) < next) next = Start(j);+ lo = hi = o = Math.Max(1.0 / 256, Math.Min(next, BarEnd(s)) - s);+ }+ if (clip) { double lim = BarEnd(s) - s; lo = Math.Min(lo, lim); hi = Math.Min(hi, lim); o = Math.Min(o, lim); }+ notes[i] = new Note(s, Math.Max(1.0 / 256, o), lo, hi);+ }+ return notes;+ }++ internal static string Ms(double ms) => ms >= 1000 ? $"{ms / 1000:0.00} s" : $"{Math.Round(ms):0} ms";++ /// <summary>Full view: note labels, output tags and the ruler.</summary>+ public bool Full { get; init; } = true;++ private Note[] _notes = Array.Empty<Note>();+ private double _now, _bpm = 120;+ private bool _off;++ public LengthGateViz() { MinHeight = 40; ClipToBounds = true; }++ public void Set(Note[] notes, double nowBeats, double bpm, bool bypassed)+ {+ _notes = notes; _now = nowBeats; _bpm = bpm > 0 ? bpm : 120; _off = bypassed;InvalidateVisual();}+ private static FormattedText Text(string s, Typeface tf, double size, IBrush ink)+ => new(s, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, tf, size, ink);+public override void Render(DrawingContext ctx){double w = Bounds.Width, h = Bounds.Height;if (w <= 0 || h <= 0) return;- NotaGraph.Window(ctx, new Rect(0, 0, w, h));- double padX = 8, padTop = 6, padBot = 14;- // Header.- ctx.DrawText(new FormattedText("GATE", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, NotaFonts.SansBold, 8, Muted), new Point(padX, padTop));- double bars = _bpm > 0 ? 4.0 * 60000.0 / _bpm : 2000; // one 4/4 bar in ms- var hdr = new FormattedText($"1 bar at {_bpm:0}\u2009BPM", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, Muted);- ctx.DrawText(hdr, new Point(w - padX - hdr.Width, padTop));-- double labelW = 26;- double x0 = padX + labelW, x1 = w - padX, top = padTop + 14, bot = h - padBot;- double rowH = (bot - top) / 2 - 3;-- void Bar(int idx, string label, double ms)+ double labelW = Full ? 43 : 0, rulerH = Full ? 12 : 0;+ var win = new Rect(labelW, 0, Math.Max(10, w - labelW), Math.Max(10, h - rulerH));+ double msPerBeat = 60000.0 / _bpm;+ int n = Math.Max(1, _notes.Length);+ double rowH = win.Height / n;+ double X(double beat) => win.X + Math.Clamp(beat / Window, 0, 1) * win.Width;++ ctx.DrawRectangle(Well, new Pen(WellEdge, 1), new RoundedRect(win.Deflate(0.5), 4));+ using (ctx.PushClip(new RoundedRect(win.Deflate(1), 3))){- double y = top + idx * (rowH + 6);- var lt = new FormattedText(label, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, Muted);- ctx.DrawText(lt, new Point(padX, y + rowH / 2 - lt.Height / 2));- ctx.DrawRectangle(Track, null, new Rect(x0, y, x1 - x0, rowH), 3, 3);- double frac = Math.Clamp(ms / FullMs, 0, 1);- if (frac > 0.001)- ctx.DrawRectangle(idx == 0 ? Amber : AmberDim, null, new Rect(x0, y, Math.Max(2, frac * (x1 - x0)), rowH), 3, 3);- var vt = new FormattedText(ms >= 1000 ? $"{ms / 1000:0.00}\u2009s" : $"{ms:0}\u2009ms", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, Sub);- double vx = x0 + frac * (x1 - x0) + 5; if (vx + vt.Width > x1) vx = x1 - vt.Width - 5;- ctx.DrawText(vt, new Point(vx, y + rowH / 2 - vt.Height / 2));+ for (double b = 0.5; b < Window - 1e-6; b += 0.5)+ ctx.FillRectangle(Math.Abs(b % 1) < 1e-6 ? BeatLine : HalfLine, new Rect(Math.Round(X(b)), win.Y, 1, win.Height));+ ctx.FillRectangle(PastBar, new Rect(X(Bar), win.Y, win.Right - X(Bar), win.Height));++ double pad = Full ? 5 : Math.Min(5, rowH * 0.18), radius = Full ? 2 : 1;+ for (int i = 0; i < _notes.Length; i++)+ {+ var nt = _notes[i]; var inp = Input[i];+ double top = win.Y + i * rowH + pad, hh = Math.Max(2, rowH - 2 * pad), cy = win.Y + (i + 0.5) * rowH;+ bool lit = !_off && _now >= nt.Start && _now < nt.Start + nt.Out;+ // Random band behind, output fill, input outline.+ if (nt.Hi - nt.Lo > 1e-4)+ ctx.FillRectangle(Band, new Rect(X(nt.Start + nt.Lo), cy - 1.5, Math.Max(0, X(nt.Start + nt.Hi) - X(nt.Start + nt.Lo)), 3));+ double ox = X(nt.Start), oe = X(nt.Start + nt.Out);+ ctx.DrawRectangle(_off ? FillOff : lit ? FillLit : Fill, null, new RoundedRect(new Rect(ox, top, Math.Max(1.5, oe - ox), hh), radius));+ double ix = X(inp.T), ie = X(inp.T + inp.Len);+ ctx.DrawRectangle(null, new Pen(Outline, 1), new RoundedRect(new Rect(ix + 0.5, top + 0.5, Math.Max(1, ie - ix - 1), Math.Max(1, hh - 1)), radius));+ if (Full)+ {+ var tag = Text(Ms(nt.Out * msPerBeat), NotaFonts.Mono, 7, lit ? FillLit : TagInk);+ double tx = Math.Min(Math.Max(Math.Max(oe, ie), X(nt.Start + nt.Hi)), win.X + win.Width * 0.88) + 5;+ ctx.DrawText(tag, new Point(tx, top + hh / 2 - tag.Height / 2));+ }+ }+ ctx.FillRectangle(Head, new Rect(Math.Round(X(_now)), win.Y, 1, win.Height));}- bool spread = Math.Abs(_maxMs - _minMs) > 1;- if (spread) { Bar(0, "max", _maxMs); Bar(1, "min", _minMs); }- else Bar(0, "len", _minMs);- // Axis ticks 0 / 500ms / 1.0s / 2.0s.- void Tick(double ms, string lbl) { double tx = x0 + Math.Clamp(ms / FullMs, 0, 1) * (x1 - x0); var ft = new FormattedText(lbl, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 7, Axis); ctx.DrawText(ft, new Point(Math.Min(tx, x1 - ft.Width), bot + 2)); }- Tick(0, "0"); Tick(500, "500\u2009ms"); Tick(1000, "1.0\u2009s"); Tick(2000, "2.0\u2009s");+ if (!Full) return;+ // Row labels: note name + velocity.+ for (int i = 0; i < _notes.Length; i++)+ {+ var inp = Input[i];+ bool lit = !_off && _now >= _notes[i].Start && _now < _notes[i].Start + _notes[i].Out;+ var name = Text(DeviceCardKit.NoteName(inp.Key), NotaFonts.Mono, 8, lit ? FillLit : Label);+ var vel = Text($"vel {inp.Vel}", NotaFonts.Mono, 6, VelInk);+ double cy = win.Y + (i + 0.5) * rowH, th = name.Height + vel.Height - 2;+ ctx.DrawText(name, new Point(0, cy - th / 2));+ ctx.DrawText(vel, new Point(0, cy - th / 2 + name.Height - 2));+ }+ // Ruler: one label per beat, in time at the current tempo.+ for (int b = 0; b <= (int)Window; b++)+ {+ string s = b == 0 ? "0" : b * msPerBeat >= 1000 ? $"{b * msPerBeat / 1000:0.0#} s" : $"{b * msPerBeat:0} ms";+ var ft = Text(s, NotaFonts.Mono, 7, Axis);+ double x = X(b) - (b == 0 ? 0 : b == (int)Window ? ft.Width : ft.Width / 2);+ ctx.DrawText(ft, new Point(x, win.Bottom + 2));+ }}}diff --git a/src/managed/Nota.App/Controls/RandomOutputViz.cs b/src/managed/Nota.App/Controls/RandomOutputViz.csnew file mode 100644index 00000000..fadc8731--- /dev/null+++ b/src/managed/Nota.App/Controls/RandomOutputViz.cs@@ -0,0 +1,272 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Random visualisers (almanac mockups 1a / 1b):+// • RandomModel — the device's roll, ported exactly from MidiRandom.h (hash, draw, the per-bar+// key), applied to a one-bar demo phrase of eight eighth notes. So the picture is what the+// device plays: with the seed Locked it is the very roll you hear, every bar.+// • RandomOutputViz — the OUTPUT window: each input note as a dashed outline, the output as a+// brass fill (brightness = velocity, the Timing delay as a shift right), a thin link when the+// pitch moved, × on a skipped note, octave lines (C) and a playhead; the note under the+// playhead lights Brass Light. The full view adds the C labels in a left gutter.+// • RandomHistViz — the DICE histogram: 1500 draws from the same generator for the current+// distribution and seed, in 17 bins across −max … centre … +max.++using System;+using System.Globalization;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Media;++namespace Nota.App;++internal static class RandomModel+{+ // Param indices — mirror MidiRandom.h.+ internal const int PChance = 0, PNoteRange = 1, PVelAmt = 2, PTimeAmt = 3, PSkip = 4, POctAmt = 5,+ PDist = 6, PRate = 7, PStayInScale = 8, PLocked = 9, PSeed = 10, PView = 11, PLockBar = 12;+ internal const double BarBeats = 4.0, MaxDelayMs = 100.0;++ /// <summary>The demo phrase: C4 E4 G4 C5 B4 G4 E4 D4 on the eighths, velocity 96.</summary>+ internal static readonly (int Pitch, double T, double Len, int Vel)[] Input =+ {+ (60, 0.0, 0.4, 96), (64, 0.5, 0.4, 96), (67, 1.0, 0.4, 96), (72, 1.5, 0.4, 96),+ (71, 2.0, 0.4, 96), (67, 2.5, 0.4, 96), (64, 3.0, 0.4, 96), (62, 3.5, 0.4, 96),+ };++ /// <summary>One note as the device plays it: output pitch / start (beats, in the bar) /+ /// velocity (1..127), whether Chance hit it and whether it was skipped.</summary>+ internal readonly record struct Note(int InPitch, double InT, double Len, int InVel, int OutPitch, double OutT, int OutVel, bool Hit, bool Skip)+ {+ public bool Changed => Hit && !Skip && (OutPitch != InPitch || OutVel != InVel || OutT - InT > 1e-4);+ }++ // ---- exact ports of MidiRandom.h ----------------------------------------------------------+ internal static uint Hash(uint a, uint b)+ {+ unchecked+ {+ uint h = a * 2654435761u + b * 40503u + 0x9e3779b9u;+ h ^= h >> 15; h *= 0x2c1b3c6du; h ^= h >> 12; return h;+ }+ }+ internal static float U01(ref uint s) { unchecked { s = s * 1664525u + 1013904223u; } return (s >> 8) / 16777216.0f; }+ internal static float Draw(int dist, ref uint s, ref float walk)+ {+ if (dist == 1) return U01(ref s) * 2f - 1f;+ if (dist == 2)+ {+ walk += (U01(ref s) * 2f - 1f) * 0.45f;+ if (walk > 1f) walk = 2f - walk;+ if (walk < -1f) walk = -2f - walk;+ return walk;+ }+ float a = Math.Max(U01(ref s), 1e-9f), b = U01(ref s);+ float g = MathF.Sqrt(-2f * MathF.Log(a)) * MathF.Cos(6.2831853f * b);+ return Math.Clamp(g / 2.6f, -1f, 1f);+ }+ internal static int SnapToCMajor(int p)+ {+ int pc = ((p % 12) + 12) % 12;+ return pc is 1 or 3 or 6 or 8 or 10 ? p - 1 : p;+ }+ internal static uint RollKey(uint seed, uint barKey) { unchecked { return Hash(seed * 7919u + 17u, barKey * 104729u + 3u); } }+ private static int LRound(double v) => (int)Math.Round(v, MidpointRounding.AwayFromZero);++ internal static int Dist(Func<int, float> g) => Math.Clamp(LRound(g(PDist)), 0, 2);+ internal static int Seed(Func<int, float> g) => LRound(Math.Max(0, g(PSeed)));+ internal static bool Locked(Func<int, float> g) => g(PLocked) >= 0.5f;++ /// <summary>The demo bar as rolled for <paramref name="bar"/> (Locked: the held Lock Bar); the+ /// Timing delay is converted to beats at <paramref name="bpm"/>.</summary>+ internal static Note[] Compute(Func<int, float> g, int bar, double bpm)+ {+ float chance = Math.Clamp(g(PChance), 0f, 1f), velAmt = Math.Clamp(g(PVelAmt), 0f, 1f), timeAmt = Math.Clamp(g(PTimeAmt), 0f, 1f);+ float skipAmt = Math.Clamp(g(PSkip), 0f, 1f), octAmt = Math.Clamp(g(POctAmt), 0f, 1f);+ int nr = Math.Clamp(LRound(g(PNoteRange)), 0, 12), dist = Dist(g);+ bool perBar = g(PRate) >= 0.5f, stay = g(PStayInScale) >= 0.5f;+ uint barKey = Locked(g) ? (uint)LRound(Math.Max(0, g(PLockBar))) : (uint)Math.Max(0, bar);+ uint roll = RollKey((uint)Seed(g), barKey);++ var walk = new float[4];+ var barD = new float[4];+ uint bs = Hash(roll, 0xB0B5EEDu); var w0 = new float[4];+ for (int d = 0; d < 4; d++) barD[d] = Draw(dist, ref bs, ref w0[d]);++ var notes = new Note[Input.Length];+ for (int i = 0; i < Input.Length; i++)+ {+ var n = Input[i];+ int tick = LRound(n.T * 480.0);+ uint nk; unchecked { nk = Hash(roll, (uint)tick * 128u + (uint)n.Pitch); }+ uint hs = Hash(nk, 0xA5A5A5A5u);+ bool hit = U01(ref hs) < chance;+ bool skip = hit && U01(ref hs) < skipAmt;+ var D = new float[4];+ if (perBar) Array.Copy(barD, D, 4);+ else { uint ds = Hash(nk, 0x3c6ef35fu); for (int d = 0; d < 4; d++) D[d] = Draw(dist, ref ds, ref walk[d]); }++ int op = n.Pitch, ov = n.Vel; double ot = n.T;+ if (hit)+ {+ op = n.Pitch + LRound(D[0] * nr) + 12 * LRound(D[3] * octAmt * 2f);+ if (stay) op = SnapToCMajor(op);+ op = Math.Clamp(op, 0, 127);+ float vel = Math.Clamp(n.Vel / 127f + D[1] * velAmt * 64f / 127f, 1f / 127f, 1f);+ ov = Math.Clamp(LRound(vel * 127), 1, 127);+ ot = n.T + Math.Abs(D[2]) * timeAmt * MaxDelayMs * (bpm > 0 ? bpm : 120) / 60000.0; // ms → beats+ }+ notes[i] = new Note(n.Pitch, n.T, n.Len, n.Vel, op, ot, ov, hit, skip);+ }+ return notes;+ }++ /// <summary>Normalised 17-bin histogram of 1500 draws (seeded by the seed) for a distribution.</summary>+ internal static double[] Histogram(int dist, int seed)+ {+ const int bins = 17;+ var h = new double[bins];+ uint s; unchecked { s = Hash((uint)seed * 31u + 5u, 0x51EDu); }+ float w = 0;+ for (int i = 0; i < 1500; i++)+ {+ float v = Draw(dist, ref s, ref w);+ h[Math.Min(bins - 1, (int)Math.Floor((v + 1) / 2 * bins))]++;+ }+ double mx = 1; foreach (var b in h) mx = Math.Max(mx, b);+ for (int i = 0; i < bins; i++) h[i] /= mx;+ return h;+ }+}++internal sealed class RandomOutputViz : Control+{+ private static readonly IBrush Well = NotaPalette.BgSunken;+ private static readonly IBrush Edge = NotaPalette.GraphBorder;+ private static readonly IBrush Quarter = NotaPalette.GraphBorder;+ private static readonly IBrush Eighth = NotaPalette.SurfaceCard;+ private static readonly IBrush Link = NotaPalette.BorderStrong;+ private static readonly IBrush Fill = NotaPalette.Accent;+ private static readonly IBrush FillLit = NotaPalette.AccentBright;+ private static readonly IBrush OutlineHit = NotaPalette.TextMuted;+ private static readonly IBrush OutlineMiss = NotaPalette.TextDisabled;+ private static readonly IBrush Mark = NotaPalette.TextMuted;+ private static readonly IBrush Head = NotaPalette.Wash(NotaPalette.AccentBright, 0xB3);+ private static readonly IBrush Axis = NotaPalette.TextTertiary;++ /// <summary>Full view: the C labels in a left gutter, larger marks.</summary>+ public bool Full { get; init; } = true;++ private RandomModel.Note[] _notes = Array.Empty<RandomModel.Note>();+ private double _now;+ private bool _off;++ public RandomOutputViz() { MinHeight = 40; ClipToBounds = true; }++ public void Set(RandomModel.Note[] notes, double nowBeats, bool bypassed)+ {+ _notes = notes; _now = nowBeats; _off = bypassed;+ InvalidateVisual();+ }++ private static FormattedText Text(string s, double size, IBrush ink)+ => new(s, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, NotaFonts.Mono, size, ink);++ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width, h = Bounds.Height;+ if (w <= 0 || h <= 0 || _notes.Length == 0) return;+ double gutter = Full ? 22 : 0;+ var win = new Rect(gutter, 0, Math.Max(10, w - gutter), h);++ // Pitch span: every in / out pitch ±2, at least two octaves.+ int lo = int.MaxValue, hi = int.MinValue;+ foreach (var n in _notes) { lo = Math.Min(lo, Math.Min(n.InPitch, n.OutPitch)); hi = Math.Max(hi, Math.Max(n.InPitch, n.OutPitch)); }+ lo -= 2; hi += 2;+ if (hi - lo < 24) { double c = (hi + lo) / 2.0; lo = (int)Math.Round(c - 12, MidpointRounding.AwayFromZero); hi = lo + 24; }+ double row = win.Height / (hi - lo);+ double Y(int p) => win.Y + (hi - p - 0.5) * row;+ double X(double beat) => win.X + beat / RandomModel.BarBeats * win.Width;++ ctx.DrawRectangle(Well, new Pen(Edge, 1), new RoundedRect(win.Deflate(0.5), 4));+ using (ctx.PushClip(new RoundedRect(win.Deflate(1), 3)))+ {+ for (int p = (int)Math.Ceiling(lo / 12.0) * 12; p <= hi; p += 12)+ ctx.FillRectangle(Edge, new Rect(win.X, Math.Round(win.Y + (hi - p) * row), win.Width, 1));+ for (int i = 1; i < 8; i++)+ ctx.FillRectangle(i % 2 == 0 ? Quarter : Eighth, new Rect(Math.Round(X(i * 0.5)), win.Y, 1, win.Height));++ double radius = Full ? 2 : 1, nh = row + 2;+ var dash = new Pen(OutlineHit, 1, new DashStyle(new double[] { 2, 2 }, 0));+ var dashMiss = new Pen(OutlineMiss, 1, new DashStyle(new double[] { 2, 2 }, 0));+ foreach (var n in _notes)+ {+ double gx = X(n.InT), gy = Y(n.InPitch) - 1, nw = X(n.Len) - X(0);+ double ox = X(n.OutT), oy = Y(n.OutPitch) - 1;+ if (!n.Skip && n.OutPitch != n.InPitch)+ {+ double y0 = Math.Min(gy, oy) + row / 2 + 1, y1 = Math.Max(gy, oy) + row / 2 + 1;+ ctx.FillRectangle(Link, new Rect(Math.Round(ox + nw / 2), y0, 1, y1 - y0));+ }+ ctx.DrawRectangle(null, n.Hit ? dash : dashMiss, new RoundedRect(new Rect(gx + 0.5, gy + 0.5, Math.Max(1, nw - 1), Math.Max(1, nh - 1)), radius));+ if (!n.Skip && !_off)+ {+ bool lit = _now >= n.OutT && _now < n.OutT + n.Len;+ using (ctx.PushOpacity(0.35 + 0.65 * n.OutVel / 127.0))+ ctx.DrawRectangle(lit ? FillLit : Fill, null, new RoundedRect(new Rect(ox, oy, nw, nh), radius));+ }+ if (n.Skip)+ {+ var x = Text("×", Full ? 8 : 7, Mark);+ ctx.DrawText(x, new Point(gx + nw / 2 - x.Width / 2, gy + nh / 2 - x.Height / 2));+ }+ }+ if (!_off) ctx.FillRectangle(Head, new Rect(Math.Round(X(_now)), win.Y, 1, win.Height));+ }++ if (!Full) return;+ for (int p = (int)Math.Ceiling(lo / 12.0) * 12; p <= hi; p += 12)+ {+ var ft = Text(DeviceCardKit.NoteName(p), 7, Axis);+ double y = Math.Clamp(win.Y + (hi - p) * row - ft.Height / 2, 0, h - ft.Height);+ ctx.DrawText(ft, new Point(gutter - 4 - ft.Width, y));+ }+ }+}++internal sealed class RandomHistViz : Control+{+ private static readonly IBrush Well = NotaPalette.BgSunken;+ private static readonly IBrush Edge = NotaPalette.GraphBorder;+ private static readonly IBrush Bar = NotaPalette.Ink("#B8862E");+ private static readonly IBrush Centre = NotaPalette.AccentBright;++ private double[] _bins = Array.Empty<double>();+ private int _dist = -1, _seed = -1;++ public RandomHistViz() { MinHeight = 20; }++ public void Set(int dist, int seed)+ {+ if (dist == _dist && seed == _seed) return;+ _dist = dist; _seed = seed; _bins = RandomModel.Histogram(dist, seed);+ InvalidateVisual();+ }++ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width, h = Bounds.Height;+ if (w <= 0 || h <= 0) return;+ ctx.DrawRectangle(Well, new Pen(Edge, 1), new RoundedRect(new Rect(0, 0, w, h).Deflate(0.5), 3));+ int n = _bins.Length;+ if (n == 0) return;+ double x0 = 3, x1 = w - 3, top = 3, bot = h - 1, gap = 1;+ double bw = (x1 - x0 - gap * (n - 1)) / n;+ for (int i = 0; i < n; i++)+ {+ double bh = Math.Max(2, _bins[i] * (bot - top));+ ctx.DrawRectangle(i == n / 2 ? Centre : Bar, null,+ new RoundedRect(new Rect(x0 + i * (bw + gap), bot - bh, Math.Max(1, bw), bh), 1, 1, 0, 0));+ }+ }+}diff --git a/src/managed/Nota.App/Controls/ScaleNoteMap.cs b/src/managed/Nota.App/Controls/ScaleNoteMap.csnew file mode 100644index 00000000..0eec4757--- /dev/null+++ b/src/managed/Nota.App/Controls/ScaleNoteMap.cs@@ -0,0 +1,188 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Scale NOTE MAP (almanac mockups 1a / 1b): the twelve pitch classes C → B as a row of+// key-shaped cells — the black keys shorter and hung from the top, the white ones standing on+// the bottom. Scale notes are filled Brass Deep with a brass edge, the root gets a Brass Light+// edge and "root", every other note names where Fold sends it ("→ D"). Clicking a cell toggles+// it (the owner switches the scale to Custom). The note sounding now lights up: its input cell+// brightens under a Brass Light ring, the cell it folded onto gets a fainter ring — and both+// fade out over a few frames after the key is released (the owner feeds Hit / Held each tick).++using System;+using System.Globalization;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using Avalonia.Media;++namespace Nota.App;++internal sealed class ScaleNoteMap : Control+{+ private static readonly string[] Names = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };+ private static readonly bool[] Black = { false, true, false, true, false, false, true, false, true, false, true, false };+ private const double FadePerSecond = 4.5; // a released note's glow is gone in ≈ ¼ s++ private readonly double[] _in = new double[12], _out = new double[12];+ private int _hover = -1;+ private DateTime _last = DateTime.UtcNow;++ public ScaleNoteMap()+ {+ ClipToBounds = false;+ Cursor = new Cursor(StandardCursorType.Hand);+ }++ /// <summary>The mini card's map: tighter gaps, smaller type, "R" for the root.</summary>+ public bool Mini { get; init; }++ public int Root { get; private set; }+ public int Mask { get; private set; } // 12 bits relative to Root+ public int Fold { get; private set; } // 0 Nearest / 1 Down / 2 Up++ /// <summary>A pitch class was clicked (absolute, 0 = C).</summary>+ public event Action<int>? Toggled;++ /// <summary>The scale shown. Repaints only on a change.</summary>+ public void SetScale(int root, int mask, int fold)+ {+ if (root == Root && mask == Mask && fold == Fold) return;+ Root = root; Mask = mask; Fold = fold;+ InvalidateVisual();+ }++ /// <summary>One animation tick: <paramref name="heldIn"/> / <paramref name="heldOut"/> are the+ /// pitch classes sounding now (12-bit), <paramref name="hitIn"/> / <paramref name="hitOut"/>+ /// those that started since the last tick — a note shorter than a frame still flashes.</summary>+ public void Animate(int heldIn, int heldOut, int hitIn, int hitOut)+ {+ var now = DateTime.UtcNow;+ double dt = Math.Clamp((now - _last).TotalSeconds, 0, 0.25);+ _last = now;+ bool dirty = false;+ void Step(double[] a, int held, int hit)+ {+ for (int pc = 0; pc < 12; pc++)+ {+ double v = ((held | hit) >> pc & 1) != 0 ? 1.0 : Math.Max(0, a[pc] - dt * FadePerSecond);+ if (Math.Abs(v - a[pc]) > 1e-4) { a[pc] = v; dirty = true; }+ }+ }+ Step(_in, heldIn, hitIn);+ Step(_out, heldOut, hitOut);+ if (dirty) InvalidateVisual();+ }++ public bool InScale(int pc) => (Mask >> Rel(pc) & 1) != 0;+ private int Rel(int pc) => ((pc - Root) % 12 + 12) % 12;++ /// <summary>Where Fold sends an out-of-scale pitch class (absolute); itself when in scale / empty.</summary>+ public int Target(int pc) => FoldTarget(pc, Root, Mask, Fold);++ public static int FoldTarget(int pc, int root, int mask, int fold)+ {+ int rel = ((pc - root) % 12 + 12) % 12;+ bool Has(int x) => (mask >> ((x % 12 + 12) % 12) & 1) != 0;+ if (mask == 0 || Has(rel)) return pc;+ int d = 0;+ if (fold == 1) { for (int k = 1; k < 12; k++) if (Has(rel - k)) { d = -k; break; } }+ else if (fold == 2) { for (int k = 1; k < 12; k++) if (Has(rel + k)) { d = k; break; } }+ else { for (int k = 1; k < 7; k++) { if (Has(rel + k)) { d = k; break; } if (Has(rel - k)) { d = -k; break; } } }+ return ((pc + d) % 12 + 12) % 12;+ }++ // ---- geometry --------------------------------------------------------------------------------+ private double Gap => Mini ? 2 : 3;+ private Rect CellRect(int pc)+ {+ double w = Bounds.Width, h = Bounds.Height, gap = Gap;+ double cw = (w - gap * 11) / 12.0;+ double x = pc * (cw + gap);+ double ch = h * (Black[pc] ? 0.78 : 0.92);+ double y = Black[pc] ? 0 : h - ch;+ return new Rect(x, y, Math.Max(1, cw), ch);+ }+ private int HitCell(Point p)+ {+ double w = Bounds.Width, gap = Gap, cw = (w - gap * 11) / 12.0;+ if (cw <= 0) return -1;+ int pc = (int)Math.Floor(p.X / (cw + gap));+ return pc is >= 0 and < 12 ? pc : -1;+ }++ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ base.OnPointerPressed(e);+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;+ int pc = HitCell(e.GetPosition(this));+ if (pc < 0) return;+ e.Handled = true;+ Toggled?.Invoke(pc);+ }+ protected override void OnPointerMoved(PointerEventArgs e)+ {+ base.OnPointerMoved(e);+ int pc = HitCell(e.GetPosition(this));+ if (pc != _hover) { _hover = pc; InvalidateVisual(); }+ }+ protected override void OnPointerExited(PointerEventArgs e)+ {+ base.OnPointerExited(e);+ if (_hover != -1) { _hover = -1; InvalidateVisual(); }+ }++ // ---- paint -------------------------------------------------------------------------------------+ private static Color Mix(Color a, Color b, double t)+ {+ t = Math.Clamp(t, 0, 1);+ byte L(byte x, byte y) => (byte)Math.Round(x + (y - x) * t);+ return Color.FromArgb(L(a.A, b.A), L(a.R, b.R), L(a.G, b.G), L(a.B, b.B));+ }+ private static Color Over(Color top, byte alpha, Color under) => Mix(under, Color.FromRgb(top.R, top.G, top.B), alpha / 255.0);++ public override void Render(DrawingContext ctx)+ {+ if (Bounds.Width <= 0 || Bounds.Height <= 0) return;+ var card = NotaPalette.SurfaceCard.Color;+ var brass = NotaPalette.Accent.Color;+ var lit = NotaPalette.AccentBright.Color;+ var deep = Over(brass, 0x1A, card); // Brass Deep fill (#2A2317 in Graphite)+ var deepLive = Over(brass, 0x44, card); // …while it sounds (#4A3A1C)+ Color offWhite = NotaPalette.GridRow.Color, offBlack = NotaPalette.BgSunken.Color, offLive = NotaPalette.TrackOff.Color;+ double r = Mini ? 2 : 3;+ double nameFs = Mini ? 7 : 9, subFs = 7, padB = Mini ? 4 : 6, gapT = Mini ? 2 : 3;+ var sans = NotaFonts.SansSemiBold;+ var mono = NotaFonts.Mono;++ for (int pc = 0; pc < 12; pc++)+ {+ var rc = CellRect(pc);+ bool inS = InScale(pc), isRoot = Rel(pc) == 0;+ double a = _in[pc], o = _out[pc];+ var baseFill = inS ? deep : Black[pc] ? offBlack : offWhite;+ var fill = Mix(baseFill, inS ? deepLive : offLive, Math.Max(a, o * 0.55));+ IBrush edge = isRoot ? NotaPalette.AccentBright : inS ? NotaPalette.AccentDim : pc == _hover ? NotaPalette.BorderStrong : NotaPalette.BorderDefault;+ ctx.DrawRectangle(new SolidColorBrush(fill), new Pen(edge, 1), rc.Deflate(0.5), r, r);+ if (pc == _hover && inS) ctx.DrawRectangle(null, new Pen(NotaPalette.Wash(NotaPalette.AccentBright, 0x60), 1), rc.Deflate(1.5), r - 1, r - 1);++ // The live ring: 1px outside the edge (the mockup's box-shadow), full for the key+ // played, fainter for the note it folded onto.+ double ring = Math.Max(a, o * 0.5);+ if (ring > 0.01)+ ctx.DrawRectangle(null, new Pen(new SolidColorBrush(Color.FromArgb((byte)Math.Round(255 * ring), lit.R, lit.G, lit.B)), 1),+ rc.Inflate(0.5), r + 1, r + 1);++ // Name + what happens to it, standing on the cell's bottom.+ var nameInk = inS ? NotaPalette.TextPrimary : NotaPalette.TextTertiary;+ string sub = isRoot ? (Mini ? "R" : "root") : inS ? "·" : Mini ? Names[Target(pc)] : "→ " + Names[Target(pc)];+ IBrush subInk = isRoot ? NotaPalette.AccentBright : inS ? NotaPalette.Accent : NotaPalette.TextSecondary;+ if (Mask == 0) { sub = Mini ? "" : "thru"; subInk = NotaPalette.TextAxis; }+ var subFt = new FormattedText(sub, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, mono, subFs, subInk);+ var nameFt = new FormattedText(Names[pc], CultureInfo.InvariantCulture, FlowDirection.LeftToRight, sans, nameFs, nameInk);+ double yb = rc.Bottom - padB;+ if (subFt.Width <= rc.Width) ctx.DrawText(subFt, new Point(rc.X + (rc.Width - subFt.Width) / 2, yb - subFt.Height));+ ctx.DrawText(nameFt, new Point(rc.X + (rc.Width - nameFt.Width) / 2, yb - subFt.Height - gapT - nameFt.Height + 2));+ }+ }+}diff --git a/src/managed/Nota.App/DeviceCards/Midi/LengthMidiBody.cs b/src/managed/Nota.App/DeviceCards/Midi/LengthMidiBody.csindex 8d2d2552..cb569ce7 100644--- a/src/managed/Nota.App/DeviceCards/Midi/LengthMidiBody.cs+++ b/src/managed/Nota.App/DeviceCards/Midi/LengthMidiBody.cs@@ -1,194 +1,425 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Detail · Devices — the Nota Length editor (MIDI effect kind 3), mockup 3b (700×260 on the-// shared shell): a LIVE strip (length Mode — Sync / ms / Gate % — with its rate + LENGTH-// control, and the On note-on / On note-off trigger) over a body of the GATE viz (the forced-// length drawn on a time axis) beside a MODIFIERS rail (Vel→Len · Key→Len · Random, Legato,-// Clip length limit). Was "Nota Note Length".+// Detail · Devices — the Nota Length editor (MIDI effect kind 3), 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 — LENGTH (mode Sync / ms / Gate %, the big value, its slider, the eight+// sync divisions, Start from note-on / note-off) | GATE (one bar of five demo notes: the+// input outlined, the output filled, Random's range as a band, a playhead) | MODIFIERS+// (bipolar Vel → Len and Key → Len, Random, Legato, Clip length limit) — over a status line.+// • S 260 × 260 — the mode chip and value over the GATE window and four knobs (Length ·+// Vel · Key · Random); the footer's "from note-on" flips the start point. Legato and+// Clip are L-only controls (presets still set them).+// The playhead follows the transport's bar while it runs, and free-runs at the project tempo+// otherwise; Random re-rolls each pass. A bypassed device greys the output and stops.using System;using System.Collections.Generic;+using System.Diagnostics;+using System.Linq;using Avalonia;using Avalonia.Controls;-using Avalonia.Controls.Shapes;using Avalonia.Input;using Avalonia.Layout;using Avalonia.Media;+using Nota.Application;namespace Nota.App;internal sealed class LengthMidiBody : IMidiDeviceBody{- // Param indices — mirror MidiNoteLength.h.- private const int PRate = 0, PGate = 1, PMode = 2, PMs = 3, PPercent = 4, PTrigger = 5,- PVelToLen = 6, PKeyToLen = 7, PRandom = 8, PLegato = 9, PClipLimit = 10;- private static readonly double[] Div = { 0.25, 0.5, 0.75, 1.0 };- private static readonly string[] RateLbl = { "1/16", "1/8", "1/8D", "1/4" };- private static readonly string[] Modes = { "Sync", "ms", "Gate %" };-- private static readonly IBrush HdrBg = NotaPalette.SurfaceCard;- private static readonly IBrush RailBg = NotaPalette.SurfaceInset;+ // Param indices — mirror MidiNoteLength.h (Rate 0 is the pre-Division sync rate).+ internal const int PGate = 1, PMode = 2, PMs = 3, PPercent = 4, PTrigger = 5, PVelToLen = 6, PKeyToLen = 7,+ PRandom = 8, PLegato = 9, PClipLimit = 10, PDivision = 11, PView = 12;+ internal static readonly string[] Modes = { "Sync", "ms", "Gate %" };+ internal static readonly string[] Divs = { "1/32", "1/16", "1/8", "1/4", "1/2", "1/1", "1/8.", "1/4T" };++ 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 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 Card = NotaPalette.SurfaceRaised;- private static readonly IBrush Ink = NotaPalette.TextOnAccent;- private static readonly IBrush AmberSubtle = NotaPalette.Wash(NotaPalette.Accent, 0x28);+ private static readonly IBrush Muted = NotaPalette.TextMuted;+ private static readonly IBrush Cap = NotaPalette.TextTertiary;++ // The free-running preview clock (transport stopped) — shared, so every card agrees.+ private static readonly long ClockStart = Stopwatch.GetTimestamp();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;+ var bpm = Mono("", Cap, 8);+ void Sync()+ {+ tag.Text = Modes[Math.Clamp((int)Math.Round(e.MidiEffectGetParam(t, index, PMode)), 0, 2)].ToUpperInvariant();+ bpm.Text = $"{e.Bpm:0.0} BPM";+ }+ Sync();+ ctx.AddDeviceRefresher(Sync);+ ToolTip.SetTip(tag, "Length mode");+ row.Children.Add(tag); row.Children.Add(MidiCardHeader.LearnButton(ctx)); row.Children.Add(bpm);+ }+ row.Children.Add(MidiCardHeader.SizeToggle(ctx, index, PView, () => IsMini(e, t, index)));+ return row;+ }++ // ---- value mapping ----------------------------------------------------------------------------+ /// <summary>The LENGTH control's 0..1 position for the current mode.</summary>+ internal static double LenNorm(Func<int, float> g) => Mode(g) switch+ {+ 1 => Math.Clamp(Math.Log(Math.Max(10, g(PMs)) / 10.0) / Math.Log(200), 0, 1),+ 2 => Math.Clamp((g(PPercent) - 10) / 190.0, 0, 1),+ _ => Math.Clamp(Math.Round(g(PDivision)), 0, 7) / 7.0,+ };+ internal static int LenParam(Func<int, float> g) => Mode(g) switch { 1 => PMs, 2 => PPercent, _ => PDivision };+ internal static double LenFromNorm(Func<int, float> g, double n) => Mode(g) switch+ {+ 1 => Math.Round(10 * Math.Pow(200, Math.Clamp(n, 0, 1))),+ 2 => Math.Round(10 + Math.Clamp(n, 0, 1) * 190),+ _ => Math.Round(Math.Clamp(n, 0, 1) * 7),+ };+ internal static int Mode(Func<int, float> g) => Math.Clamp((int)Math.Round(g(PMode)), 0, 2);+ internal static int Div(Func<int, float> g) => Math.Clamp((int)Math.Round(g(PDivision)), 0, Divs.Length - 1);++ internal static string LenValue(Func<int, float> g) => Mode(g) switch+ {+ 1 => LengthGateViz.Ms(g(PMs)),+ 2 => $"{Math.Round(g(PPercent)):0}\u2009%",+ _ => Divs[Div(g)],+ };+ internal static string LenSub(Func<int, float> g, double bpm) => Mode(g) switch+ {+ 1 => "fixed",+ 2 => "of input",+ _ => LengthGateViz.Ms(LengthGateViz.DivBeats[Div(g)] * Math.Clamp(g(PGate), 0.05, 2.0) * 60000.0 / (bpm > 0 ? bpm : 120)),+ };+ internal static string Signed(double v) => (v > 0.004 ? "+" : v < -0.004 ? "−" : "") + $"{Math.Abs(Math.Round(v * 100)):0}\u2009%";++ // ---- 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 Length", 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 Learn(Control c, int p, string name) => MidiLearn.Bind(c, MidiTarget.MidiDeviceParam(track, mi, p), name);double Bpm() => engine.Bpm > 0 ? engine.Bpm : 120;+ bool Bypassed() => engine.MidiEffectBypassed(track, mi);+ bool mini = IsMini(engine, track, mi);var readouts = new List<Action>();- 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(); }- // Resulting length (ms) for the current params, and its modifier spread.- double BaseMs()+ // ---- the animated model: playhead + Random's roll per pass ---------------------------------+ double now = 0; int cycle = 0;+ var notes = LengthGateViz.Compute(G, Bpm(), 0);+ void Tick(){- int mode = Gi(PMode); double bpm = Bpm();- if (mode == 1) return G(PMs);- if (mode == 2) return (60000.0 / bpm) * (G(PPercent) / 100.0); // % of a 1-beat reference- return Div[Math.Clamp(Gi(PRate), 0, 3)] * Math.Clamp(G(PGate), 0.05, 2) * (60000.0 / bpm);+ if (!Bypassed())+ {+ double pos = engine.IsPlaying+ ? engine.PositionBeats+ : Stopwatch.GetElapsedTime(ClockStart).TotalMinutes * Bpm();+ now = (pos % LengthGateViz.Bar + LengthGateViz.Bar) % LengthGateViz.Bar;+ cycle = (int)Math.Floor(pos / LengthGateViz.Bar);+ }+ notes = LengthGateViz.Compute(G, Bpm(), cycle);}+ string AvgOut() => LengthGateViz.Ms(notes.Average(n => n.Out) * 60000.0 / Bpm());+ string TrigName() => G(PTrigger) >= 0.5f ? "note-off" : "note-on";++ Tick();+ Control rootView = mini ? BuildMini() : BuildLarge();+ ctx.AddDeviceRefresher(() => { Tick(); Refresh(); });+ Refresh();+ return rootView;- // ---- generic controls ----- Control RawSlider(int p, double min, double max, Func<double, string> fmt, double w, IBrush fill, double valW = 42)+ // =========================================================================================+ Control BuildLarge(){- var val = Mono(fmt(G(p)), Txt); val.MinWidth = valW; val.TextAlignment = TextAlignment.Right;- var fillB = new Border { Height = 3, Background = fill, CornerRadius = NotaRadius.Clip, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center };- var handle = new Border { Width = 7, Height = 9, Background = Sub, CornerRadius = NotaRadius.Clip, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center };- var slot = new Panel { Height = 9, Cursor = new Cursor(StandardCursorType.Hand), Background = Brushes.Transparent };- if (w > 0) slot.Width = w;- slot.Children.Add(new Border { Height = 3, Background = Inset, CornerRadius = NotaRadius.Clip, VerticalAlignment = VerticalAlignment.Center });- slot.Children.Add(fillB); slot.Children.Add(handle);- void Vis(double v) { double W = slot.Bounds.Width, n = (v - min) / (max - min); fillB.Width = n * W; handle.Margin = new Thickness(Math.Clamp(n * W - 3.5, 0, Math.Max(0, W - 7)), 0, 0, 0); }- bool drag = false;- void SetX(double x) { double n = Math.Clamp(x / Math.Max(1, slot.Bounds.Width), 0, 1); double v = min + n * (max - min); S(p, v); Vis(v); val.Text = fmt(v); Refresh(); }- slot.PointerPressed += (_, e) => { drag = true; e.Pointer.Capture(slot); SetX(e.GetPosition(slot).X); };- slot.PointerMoved += (_, e) => { if (drag) SetX(e.GetPosition(slot).X); };- slot.PointerReleased += (_, e) => { if (drag) { drag = false; e.Pointer.Capture(null); } };- MidiLearn.Bind(slot, MidiTarget.MidiDeviceParam(track, mi, p), engine.MidiEffectParamName(track, mi, p));- slot.SizeChanged += (_, _) => Vis(G(p));- readouts.Add(() => { if (!drag) { double v = G(p); Vis(v); val.Text = fmt(v); } });- var g = new Grid { ColumnDefinitions = new ColumnDefinitions(w > 0 ? "Auto,Auto" : "*,Auto"), ColumnSpacing = 5, VerticalAlignment = VerticalAlignment.Center };- Grid.SetColumn(val, 1); g.Children.Add(slot); g.Children.Add(val);- return g;+ // ---- LENGTH ----+ var modeSeg = DeviceCardKit.Segments(Modes, () => Mode(G), i => { Begin(PMode); S(PMode, i); End(PMode); Refresh(); }, out var modeSync,+ fill: true, padX: 2, fontSize: 8);+ readouts.Add(modeSync);+ Learn(modeSeg, PMode, "Mode");+ ToolTip.SetTip(modeSeg, "Sync: a tempo division · ms: a fixed time · Gate %: a share of how long each note was held");++ var bigVal = Mono("", BrassLit, 18); bigVal.FontWeight = FontWeight.Medium; bigVal.LetterSpacing = -0.3;+ var bigSub = Mono("", Cap, 7); bigSub.VerticalAlignment = VerticalAlignment.Bottom; bigSub.Margin = new Thickness(0, 0, 0, 4);+ var valRow = new DockPanel { Children = { WithDock(bigSub, Dock.Right), bigVal } };+ bigSub.HorizontalAlignment = HorizontalAlignment.Right;++ int lenGesture = -1;+ var lenTrack = new SliderTrack { Height = 11, Reset = () => { int p = LenParam(G); Begin(p); S(p, Def(p)); End(p); Refresh(); } };+ lenTrack.Changed += n => { S(LenParam(G), LenFromNorm(G, n)); Refresh(); };+ lenTrack.GestureBegin += () => { lenGesture = LenParam(G); Begin(lenGesture); };+ lenTrack.GestureEnd += () => { if (lenGesture >= 0) End(lenGesture); lenGesture = -1; };+ ToolTip.SetTip(lenTrack, "Length — drag up / down, double-click resets");+ readouts.Add(() =>+ {+ bigVal.Text = LenValue(G); bigSub.Text = LenSub(G, Bpm());+ if (!lenTrack.Dragging) lenTrack.Norm = LenNorm(G);+ });++ var divGrid = new Grid { ColumnSpacing = 2, RowSpacing = 2, ColumnDefinitions = new ColumnDefinitions("*,*,*,*"), RowDefinitions = new RowDefinitions("14,14") };+ for (int i = 0; i < Divs.Length; i++)+ {+ int di = i;+ var tb = Mono(Divs[i], Cap, 7); tb.HorizontalAlignment = HorizontalAlignment.Center;+ var chip = new Border { CornerRadius = NotaRadius.Clip, Cursor = new Cursor(StandardCursorType.Hand), Child = tb };+ chip.PointerPressed += (_, ev) =>+ {+ if (!ev.GetCurrentPoint(chip).Properties.IsLeftButtonPressed) return;+ Begin(PDivision); S(PDivision, di); End(PDivision); Refresh(); ev.Handled = true;+ };+ ToolTip.SetTip(chip, $"{Divs[i]} note");+ readouts.Add(() =>+ {+ bool on = Div(G) == di;+ chip.Background = on ? NotaPalette.Accent : NotaPalette.GridBeat;+ tb.Foreground = on ? NotaPalette.TextOnAccent : Cap;+ });+ Grid.SetColumn(chip, i % 4); Grid.SetRow(chip, i / 4);+ divGrid.Children.Add(chip);+ }+ Learn(divGrid, PDivision, "Division");+ readouts.Add(() => divGrid.IsVisible = Mode(G) == 0);++ var trigSeg = DeviceCardKit.Segments(new[] { "Note-on", "Note-off" }, () => G(PTrigger) >= 0.5f ? 1 : 0,+ i => { Begin(PTrigger); S(PTrigger, i); End(PTrigger); Refresh(); }, out var trigSync, fill: true, padX: 2, fontSize: 8);+ readouts.Add(trigSync);+ Learn(trigSeg, PTrigger, "Start From");+ ToolTip.SetTip(trigSeg, "Count the length from the note-on, or from the note-off (the note fires when the key is released)");+ var trigBox = new Border { BorderBrush = Rule, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 6, 0, 0),+ Child = new StackPanel { Spacing = 4, Children = { Caps("START FROM"), trigSeg } } };++ var lenBody = new DockPanel { Margin = new Thickness(8, 6), Children =+ {+ WithDock(trigBox, Dock.Bottom),+ new StackPanel { Spacing = 6, Children = { modeSeg, valRow, lenTrack, divGrid } },+ } };+ var lenIsland = IslandBox(IslandHead(Caps("LENGTH"), null), lenBody, 132);++ // ---- GATE ----+ var gate = new LengthGateViz { Full = true };+ var gateInfo = Mono("", Cap, 7);+ readouts.Add(() =>+ {+ gateInfo.Text = $"1 bar at {Bpm():0} BPM · {LengthGateViz.Input.Length} notes";+ gate.Set(notes, now, Bpm(), Bypassed());+ });+ ToolTip.SetTip(gate, "Outline — the note played in · fill — the note out · band — the range Random spreads it over. The shaded part is past the bar line.");+ var gateIsland = IslandBox(IslandHead(Caps("GATE"), gateInfo), new Border { Padding = new Thickness(8, 5, 8, 4), Child = gate }, double.NaN);++ // ---- MODIFIERS ----+ var mods = new StackPanel { Spacing = 9, Children =+ {+ ModSlider("VEL → LEN", PVelToLen, true, "loud notes longer at +"),+ ModSlider("KEY → LEN", PKeyToLen, true, "low notes longer at +"),+ ModSlider("RANDOM", PRandom, false, "spread per note"),+ } };+ var flags = new Border { BorderBrush = Rule, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 6, 0, 0),+ Child = new StackPanel { Spacing = 5, Children =+ {+ Flag(PLegato, "Legato · retrigger held", "Each note lasts until the next one starts (at most to the bar line)"),+ Flag(PClipLimit, "Clip length limit", "No note crosses the bar line it started in"),+ } } };+ var modIsland = IslandBox(IslandHead(Caps("MODIFIERS"), null),+ new DockPanel { Margin = new Thickness(8, 7), Children = { WithDock(flags, Dock.Bottom), mods } }, 172);++ lenIsland.Margin = new Thickness(0, 0, 5, 0); modIsland.Margin = new Thickness(5, 0, 0, 0);+ var islands = new DockPanel { Children = { WithDock(lenIsland, Dock.Left), WithDock(modIsland, Dock.Right), gateIsland } };++ var statusL = new TextBlock { FontSize = 8, Foreground = Sub, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };+ var statusR = Mono("", Sub);+ readouts.Add(() =>+ {+ statusL.Text = $"{Modes[Mode(G)]} {LenValue(G)} · from {TrigName()} · avg out {AvgOut()}"+ + (G(PLegato) >= 0.5f ? " · legato" : "") + (G(PClipLimit) >= 0.5f ? " · clip" : "");+ statusR.Text = Bypassed() ? "bypassed" : "MIDI · latency 0 smp";+ });+ return Framed(islands, statusL, statusR);}- Control Seg(int p, string[] names, Action<int>? extra = null, 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 = 58, 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;+ Begin(PMode); S(PMode, (Mode(G) + d) % 3); End(PMode); Refresh(); ev.Handled = true;+ };+ ToolTip.SetTip(modeChip, "Length mode: Sync / ms / Gate % — click for the next, Shift-click for the previous");+ Learn(modeChip, PMode, "Mode");++ var val = Mono("", BrassLit, 9); val.FontWeight = FontWeight.Medium;+ var sub = Mono("", Cap, 7);+ var head = new DockPanel { Height = 14, Children = { WithDock(modeChip, Dock.Left), WithDock(sub, Dock.Right), val } };++ var gate = new LengthGateViz { Full = false };+ ToolTip.SetTip(gate, "Outline — in · fill — out · band — Random's range");++ var knobs = new Grid { Height = 53, ColumnDefinitions = new ColumnDefinitions("*,*,*,*") };+ var cells = new[]+ {+ KnobCell("LENGTH", () => LenParam(G), () => LenNorm(G), n => S(LenParam(G), LenFromNorm(G, n)), () => LenValue(G)),+ KnobCell("VEL", () => PVelToLen, () => (G(PVelToLen) + 1) / 2, n => S(PVelToLen, Math.Round(n * 2 - 1, 3)), () => Signed(G(PVelToLen)), 0.5),+ KnobCell("KEY", () => PKeyToLen, () => (G(PKeyToLen) + 1) / 2, n => S(PKeyToLen, Math.Round(n * 2 - 1, 3)), () => Signed(G(PKeyToLen)), 0.5),+ KnobCell("RANDOM", () => PRandom, () => G(PRandom), n => S(PRandom, Math.Round(n, 3)), () => $"±{Math.Round(G(PRandom) * 100):0}\u2009%", 0),+ };+ 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), new Border { Margin = new Thickness(0, 4), Child = gate },+ } };+ 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(G)];+ val.Text = LenValue(G); sub.Text = LenSub(G, Bpm());+ gate.Set(notes, now, Bpm(), Bypassed());+ });++ // Footer: "from note-on" flips the start point.+ 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;+ Begin(PTrigger); S(PTrigger, G(PTrigger) >= 0.5f ? 0 : 1); End(PTrigger); Refresh(); ev.Handled = true;+ };+ ToolTip.SetTip(statusL, "Count the length from the note-on or the note-off — click to switch");+ Learn(statusL, PTrigger, "Start From");+ var statusR = Mono("", Sub);+ readouts.Add(() =>+ {+ statusL.Text = $"from {TrigName()}";+ statusR.Text = Bypassed() ? "bypassed" : $"avg {AvgOut()}";+ });+ return Framed(island, statusL, statusR);}- // Outlined pill buttons (radio-style) bound to a 0/1 param — for the trigger choice.- Control TrigSeg()++ // ---- shared pieces -----------------------------------------------------------------------+ Control Framed(Control main, TextBlock left, TextBlock right){- var seg = DeviceCardKit.Segments(new[] { "On note-on", "On note-off" }, () => G(PTrigger) >= 0.5f ? 1 : 0, i => { S(PTrigger, i); Refresh(); }, out var sync);- readouts.Add(sync);- MidiLearn.Bind(seg, MidiTarget.MidiDeviceParam(track, mi, PTrigger), engine.MidiEffectParamName(track, mi, PTrigger));- return seg;+ 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 } } };}- Control Toggle(int p, string label, IBrush accent)++ Control IslandHead(Control left, Control? right){- var host = DeviceCardKit.Switch(label, () => G(p) >= 0.5f, () => { S(p, G(p) >= 0.5f ? 0 : 1); Refresh(); }, out var sync);- readouts.Add(sync);- MidiLearn.Bind(host, MidiTarget.MidiDeviceParam(track, mi, p), label);- return host;+ 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 };}- // Sync-mode rate chips.- Control RateChips()++ Border IslandBox(Control head, Control content, double width){- var seg = DeviceCardKit.Segments(RateLbl, () => Math.Clamp(Gi(PRate), 0, RateLbl.Length - 1), i => { S(PRate, i); Refresh(); }, out var sync);- readouts.Add(sync);- MidiLearn.Bind(seg, MidiTarget.MidiDeviceParam(track, mi, PRate), engine.MidiEffectParamName(track, mi, PRate));- return seg;+ 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;}- // ---- LIVE strip (Mode + contextual length + Trigger) ----- var lenHost = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center };- void BuildLen()+ // A MODIFIERS slider: caps label + value (brass once moved off neutral), the track, a hint.+ Control ModSlider(string label, int p, bool bipolar, string hint){- lenHost.Children.Clear();- int mode = Gi(PMode);- lenHost.Children.Add(Cap("LENGTH"));- if (mode == 1)- lenHost.Children.Add(RawSlider(PMs, 10, 2000, v => $"{v:0}\u2009ms", 64, Amber));- else if (mode == 2)- lenHost.Children.Add(RawSlider(PPercent, 5, 200, v => $"{v:0}\u2009%", 64, Amber));- else- {- lenHost.Children.Insert(0, RateChips()); // rate chips before LENGTH (Sync only)- lenHost.Children.Add(RawSlider(PGate, 0.05, 2.0, v => $"{Div[Math.Clamp(Gi(PRate), 0, 3)] * v * (60000.0 / Bpm()):0}\u2009ms", 64, Amber));- }+ var l = Caps(label);+ var v = Mono("", Txt); v.HorizontalAlignment = HorizontalAlignment.Right;+ Func<double> toNorm = bipolar ? () => (G(p) + 1) / 2 : () => G(p);+ Func<double, double> fromNorm = bipolar ? n => Math.Round(n * 2 - 1, 3) : n => Math.Round(n, 3);+ var trk = new SliderTrack { Height = 11, Bipolar = bipolar, Reset = () => { Begin(p); S(p, Def(p)); End(p); Refresh(); } };+ trk.Changed += n => { S(p, fromNorm(n)); Refresh(); };+ trk.GestureBegin += () => Begin(p);+ trk.GestureEnd += () => End(p);+ Learn(trk, p, label);+ ToolTip.SetTip(trk, $"{label} — drag up / down, double-click resets");+ readouts.Add(() =>+ {+ double x = G(p);+ if (!trk.Dragging) trk.Norm = toNorm();+ bool mod = Math.Abs(x) > 0.004;+ l.Foreground = mod ? BrassLit : Cap;+ v.Foreground = mod ? BrassLit : Txt;+ v.Text = bipolar ? Signed(x) : $"±{Math.Round(x * 100):0}\u2009%";+ });+ return new StackPanel { Spacing = 2, Children =+ {+ new DockPanel { Children = { WithDock(v, Dock.Right), l } }, trk,+ new TextBlock { Text = hint, FontSize = 7, Foreground = Cap },+ } };}- var modeSeg = Seg(PMode, Modes, _ => BuildLen());- var liveL = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children = { modeSeg, lenHost } };- var liveR = new StackPanel { HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, Children = { TrigSeg() } };- var liveGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };- Grid.SetColumn(liveR, 1); liveGrid.Children.Add(liveL); liveGrid.Children.Add(liveR);- var liveStrip = new Border { Height = 34, Background = HdrBg, BorderBrush = Bd, BorderThickness = new Thickness(0, 0, 0, 1), Padding = new Thickness(9, 0), Child = liveGrid };-- // ---- GATE viz ----- var gate = new LengthGateViz { VerticalAlignment = VerticalAlignment.Stretch };- readouts.Add(() =>- {- double b = BaseMs();- double vt = G(PVelToLen), rnd = G(PRandom);- double min = b * Math.Max(0.05, 1 - vt) * Math.Max(0.05, 1 - rnd);- double max = b * (1 + vt) * (1 + rnd);- gate.Set(min, max, Bpm());- });- var gateHost = new Border { Padding = new Thickness(8, 7), Child = gate };-- // ---- MODIFIERS rail ----- Control ModRow(string label, int p, Func<double, string> fmt)++ // A switch + sentence-case label (Legato / Clip length limit).+ Control Flag(int p, string label, string tip){- var lbl = Cap(label); lbl.Width = 52;- var sld = RawSlider(p, 0, 1, _ => "", 0, Teal, 0);- var val = Mono(fmt(G(p)), Txt); val.Width = 34; val.TextAlignment = TextAlignment.Right;- readouts.Add(() => val.Text = fmt(G(p)));- var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 5, VerticalAlignment = VerticalAlignment.Center };- Grid.SetColumn(sld, 1); Grid.SetColumn(val, 2);- g.Children.Add(lbl); g.Children.Add(sld); g.Children.Add(val);- return g;+ var sw = new SwitchTrack { VerticalAlignment = VerticalAlignment.Center };+ var tb = new TextBlock { Text = label, FontSize = 8, VerticalAlignment = VerticalAlignment.Center };+ var row = new Border { Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand),+ Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Children = { sw, tb } } };+ row.PointerPressed += (_, ev) =>+ {+ if (!ev.GetCurrentPoint(row).Properties.IsLeftButtonPressed) return;+ Begin(p); S(p, G(p) >= 0.5f ? 0 : 1); End(p); Refresh(); ev.Handled = true;+ };+ ToolTip.SetTip(row, tip);+ Learn(row, p, label);+ readouts.Add(() => { bool on = G(p) >= 0.5f; sw.IsOn = on; tb.Foreground = on ? Txt : Muted; });+ return row;}- var modStack = new StackPanel { Spacing = 6, Children =++ // A mini-view knob: 34px gauge, caps label, mono value. The target param may follow the mode (LENGTH).+ Control KnobCell(string label, Func<int> param, Func<double> norm, Action<double> set, Func<string> text, double resetNorm = double.NaN){- Cap("MODIFIERS"),- ModRow("VEL → LEN", PVelToLen, v => $"{v * 100:0}\u2009%"),- ModRow("KEY → LEN", PKeyToLen, v => $"{v * 100:0}\u2009%"),- ModRow("RANDOM", PRandom, v => $"±{v * 100:0}\u2009%"),- new Border { Height = 1, Background = Card, Margin = new Thickness(0, 2) },- Toggle(PLegato, "Legato · retrigger held", Amber),- Toggle(PClipLimit, "Clip length limit", Amber),- } };- var modRail = new Border { Width = 186, Background = RailBg, BorderBrush = Bd, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(8, 6), Child = modStack };-- var body = new DockPanel { LastChildFill = true };- DockPanel.SetDock(modRail, Dock.Right); body.Children.Add(modRail); body.Children.Add(gateHost);- var root = new DockPanel { LastChildFill = true, Background = NotaPalette.BgApp };- DockPanel.SetDock(liveStrip, Dock.Top); root.Children.Add(liveStrip); root.Children.Add(body);-- BuildLen();- ctx.AddDeviceRefresher(Refresh); // GATE viz follows tempo/param changes- 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); };+ knob.GestureEnd += () => { if (gesture >= 0) End(gesture); gesture = -1; };+ Learn(knob, param(), label);+ 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; v.Text = text(); });+ return new StackPanel { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Cursor = new Cursor(StandardCursorType.SizeNorthSouth),+ Children = { knob, new TextBlock { Text = label, FontSize = 7, FontWeight = FontWeight.Bold, LetterSpacing = 0.6, Foreground = Cap, HorizontalAlignment = HorizontalAlignment.Center, LineHeight = 9 }, v } };+ }}}diff --git a/src/managed/Nota.App/DeviceCards/Midi/RandomMidiBody.cs b/src/managed/Nota.App/DeviceCards/Midi/RandomMidiBody.csindex a718e19f..07df71e5 100644--- a/src/managed/Nota.App/DeviceCards/Midi/RandomMidiBody.cs+++ b/src/managed/Nota.App/DeviceCards/Midi/RandomMidiBody.cs@@ -1,164 +1,473 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Detail · Devices — the Nota Random editor (MIDI effect kind 5), mockup 3b (700×260 on the-// shared shell): a LIVE strip (Chance · Distribution Gauss/Even/Walk · Lock seed / Re-roll)-// over a body of WHAT VARIES (one row per dimension — Note · Velocity · Timing · Skip ·-// Octave — with its amount, coloured by category: pitch brass, timing teal, skip red) beside-// a DISTRIBUTION rail (the drawn shape, Rate Per note / Per bar, Stay in scale).+// Detail · Devices — the Nota Random editor (MIDI effect kind 5), 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 — WHAT VARIES (Note · Velocity · Timing · Skip · Octave, amount sliders) |+// OUTPUT (one bar of eight demo notes: the input dashed, the output filled — brightness =+// velocity, a link when the pitch moved, × when skipped — under a playhead) | DICE (Chance,+// the distribution Gauss / Even / Walk and its histogram, Per note / Per bar, seed with+// Reroll and Lock, Stay in scale) — over a status line.+// • S 260 × 260 — the distribution chip over the OUTPUT window and four knobs (Chance · Note+// · Velocity · Timing); the footer's seed rerolls and its lock holds the roll. Skip, Octave,+// Rate and Stay in scale are L-only controls (presets still set them).+// The playhead follows the transport's bar while it runs and free-runs at the project tempo+// otherwise; every bar is a new roll until the seed is locked — Lock holds the bar showing+// (its "Lock Bar"), so what you see is what keeps playing. A bypassed device greys out.using System;using System.Collections.Generic;+using System.Diagnostics;+using System.Linq;using Avalonia;using Avalonia.Controls;using Avalonia.Controls.Shapes;using Avalonia.Input;using Avalonia.Layout;using Avalonia.Media;+using Nota.Application;+using static Nota.App.RandomModel;namespace Nota.App;internal sealed class RandomMidiBody : IMidiDeviceBody{- private const int PChance = 0, PNoteRange = 1, PVelAmt = 2, PTimeAmt = 3, PSkip = 4, POctAmt = 5,- PDist = 6, PRate = 7, PStayInScale = 8, PLocked = 9, PSeed = 10;- private static readonly string[] Dists = { "Gauss", "Even", "Walk" };- private static readonly string[] Rates = { "Per note", "Per bar" };+ internal static readonly string[] Dists = { "Gauss", "Even", "Walk" };+ internal static readonly string[] Rates = { "Per note", "Per bar" };- 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 Teal = NotaPalette.Teal;- private static readonly IBrush Red = NotaPalette.Ink("#D0603F");+ private static readonly IBrush Well = NotaPalette.BgSunken;+ private static readonly IBrush Brass = NotaPalette.Accent;+ 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 Card = NotaPalette.SurfaceRaised;- private static readonly IBrush Ink = NotaPalette.TextOnAccent;- private static readonly IBrush TealSubtle = NotaPalette.Wash(NotaPalette.Teal, 0x24);+ private static readonly IBrush Muted = NotaPalette.TextMuted;+ private static readonly IBrush Cap = NotaPalette.TextTertiary;+ private static readonly IBrush Faint = NotaPalette.TextDisabled;++ // The free-running preview clock (transport stopped) — shared, so every card agrees.+ private static readonly long ClockStart = Stopwatch.GetTimestamp();public double Width => 700;public bool FullBleed => true;+ private static bool HasLayout(IAudioEngine e, int track, int mi) => e.MidiEffectParamCount(track, mi) > PLockBar;+ 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;+ var bpm = Mono("", Cap, 8);+ void Sync()+ {+ tag.Text = Dists[Math.Clamp((int)Math.Round(e.MidiEffectGetParam(t, index, PDist)), 0, 2)].ToUpperInvariant();+ bpm.Text = $"{e.Bpm:0.0} BPM";+ }+ Sync();+ ctx.AddDeviceRefresher(Sync);+ ToolTip.SetTip(tag, "Distribution");+ row.Children.Add(tag); row.Children.Add(MidiCardHeader.LearnButton(ctx)); row.Children.Add(bpm);+ }+ row.Children.Add(MidiCardHeader.SizeToggle(ctx, index, PView, () => IsMini(e, t, index)));+ return row;+ }++ // ---- formats ----------------------------------------------------------------------------------+ internal static string NoteText(double v) => $"±{Math.Round(v, MidpointRounding.AwayFromZero):0} st";+ internal static string VelText(double v) => $"±{Math.Round(v * 64, MidpointRounding.AwayFromZero):0}";+ internal static string TimeText(double v) => $"≤{Math.Round(v * MaxDelayMs, MidpointRounding.AwayFromZero):0} ms";+ internal static string SkipText(double v) => $"{Math.Round(v * 100, MidpointRounding.AwayFromZero):0} %";+ internal static string OctText(double v) => $"±{Math.Round(v * 2, MidpointRounding.AwayFromZero):0} oct";+ internal static string ChanceText(double v) => $"{Math.Round(v * 100, MidpointRounding.AwayFromZero):0} %";++ // ---- 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 Random", 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 Set(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);+ double Bpm() => engine.Bpm > 0 ? engine.Bpm : 120;+ bool Bypassed() => engine.MidiEffectBypassed(track, mi);+ bool mini = IsMini(engine, track, mi);var readouts = new List<Action>();- 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(); }- // ---- generic controls ----- Control MiniSlider(string label, int p, double min, double max, Func<double, string> fmt, double w)+ // ---- the animated model: the playhead, and a new roll per bar ------------------------------+ double now = 0; int bar = 0;+ var notes = Compute(G, 0, Bpm());+ void Tick(){- 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: 30);- MidiLearn.Bind(row, MidiTarget.MidiDeviceParam(track, mi, p), engine.MidiEffectParamName(track, mi, p));- readouts.Add(sync);- return row;+ if (!Bypassed())+ {+ double pos = engine.IsPlaying+ ? engine.PositionBeats+ : Stopwatch.GetElapsedTime(ClockStart).TotalMinutes * Bpm();+ now = (pos % BarBeats + BarBeats) % BarBeats;+ bar = Math.Max(0, (int)Math.Floor(pos / BarBeats));+ }+ notes = Compute(G, bar, Bpm());+ }+ int ShownBar() => Locked(G) ? (int)Math.Round(Math.Max(0, G(PLockBar))) : bar;+ int Changed() => notes.Count(n => n.Changed);+ int Skipped() => notes.Count(n => n.Skip);++ // Lock holds the roll showing now; Reroll moves to the next seed (1..999).+ void ToggleLock()+ {+ if (!Locked(G)) Set(PLockBar, bar);+ Set(PLocked, Locked(G) ? 0 : 1);+ Refresh();+ }+ void Reroll() { Set(PSeed, Seed(G) % 999 + 1); Refresh(); }++ Tick();+ Control rootView = mini ? BuildMini() : BuildLarge();+ ctx.AddDeviceRefresher(() => { Tick(); Refresh(); });+ Refresh();+ return rootView;++ // =========================================================================================+ Control BuildLarge()+ {+ // ---- WHAT VARIES ----+ var rows = new Grid { Margin = new Thickness(8, 4, 8, 5), RowDefinitions = new RowDefinitions("*,*,*,*,*") };+ var specs = new (string Label, int P, double Max, Func<double, string> Fmt, string Tip)[]+ {+ ("Note", PNoteRange, 12, NoteText, "Transpose up or down by up to this many semitones"),+ ("Velocity", PVelAmt, 1, VelText, "Push the velocity up or down by up to this much"),+ ("Timing", PTimeAmt, 1, TimeText, "Play late by up to this long (a live effect can't play early)"),+ ("Skip", PSkip, 1, SkipText, "Chance that a varied note is dropped"),+ ("Octave", POctAmt, 1, OctText, "Jump up or down by up to two octaves"),+ };+ for (int i = 0; i < specs.Length; i++)+ {+ var sp = specs[i];+ var row = VaryRow(sp.Label, sp.P, sp.Max, sp.Fmt, sp.Tip);+ Grid.SetRow(row, i); rows.Children.Add(row);+ }+ var varyIsland = IslandBox(IslandHead(Caps("WHAT VARIES"), Mono("amount · range", Cap, 7)), rows, 170);++ // ---- OUTPUT ----+ var viz = new RandomOutputViz { Full = true };+ ToolTip.SetTip(viz, "One bar of eight notes: dashed — the note in, filled — the note out (brightness = velocity, shifted right when delayed), × — skipped");+ var outInfo = Mono("", Cap, 7);+ readouts.Add(() =>+ {+ outInfo.Text = $"bar {ShownBar() + 1} · {Changed()} changed · {Skipped()} skipped" + (Locked(G) ? " · held" : "");+ viz.Set(notes, now, Bypassed());+ });+ var legend = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, Height = 10, Margin = new Thickness(22, 3, 0, 0), Children =+ {+ LegendItem(new Rectangle { Width = 9, Height = 5, Stroke = Muted, StrokeThickness = 1, StrokeDashArray = new Avalonia.Collections.AvaloniaList<double> { 2, 1 }, RadiusX = 1, RadiusY = 1 }, "input"),+ LegendItem(new Border { Width = 9, Height = 5, Background = Brass, CornerRadius = NotaRadius.Bar }, "output · brightness = velocity"),+ LegendItem(Mono("×", Muted, 8), "skip"),+ } };+ var outBody = new DockPanel { Margin = new Thickness(8, 5, 8, 4), Children = { WithDock(legend, Dock.Bottom), viz } };+ var outIsland = IslandBox(IslandHead(Caps("OUTPUT"), outInfo), outBody, double.NaN);++ // ---- DICE ----+ var chanceTrk = Slider(PChance, 1);+ var chanceLbl = Caps("CHANCE"); chanceLbl.Width = 38;+ var chanceVal = Mono("", Txt); chanceVal.Width = 26; chanceVal.TextAlignment = TextAlignment.Right;+ readouts.Add(() =>+ {+ bool mod = Math.Abs(G(PChance) - Def(PChance)) > 0.004;+ chanceLbl.Foreground = mod ? BrassLit : Cap;+ chanceVal.Foreground = mod ? BrassLit : Txt;+ chanceVal.Text = ChanceText(G(PChance));+ });+ ToolTip.SetTip(chanceTrk, "Chance — how many notes get varied at all");+ var chanceRow = new DockPanel { Children = { WithDock(chanceLbl, Dock.Left), WithDock(chanceVal, Dock.Right), chanceTrk } };++ var distSeg = Seg(PDist, Dists, "Distribution: Gauss — mostly small moves · Even — any amount equally · Walk — drifts from note to note");+ var hist = new RandomHistViz();+ ToolTip.SetTip(hist, "The shape of the roll — 1500 draws from the same generator");+ readouts.Add(() => hist.Set(Dist(G), Seed(G)));+ var axis = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto") };+ var ac = Mono("centre", Faint, 6); ac.HorizontalAlignment = HorizontalAlignment.Center; Grid.SetColumn(ac, 1);+ var ar = Mono("+max", Faint, 6); Grid.SetColumn(ar, 2);+ axis.Children.Add(Mono("−max", Faint, 6)); axis.Children.Add(ac); axis.Children.Add(ar);+ var histBox = new DockPanel { Children = { WithDock(axis, Dock.Bottom), hist } };+ axis.Margin = new Thickness(0, 2, 0, 0);++ var rateSeg = Seg(PRate, Rates, "Per note — every note rolls its own values · Per bar — one set of values for the whole bar");++ var seedTb = Mono("", Txt);+ readouts.Add(() => seedTb.Text = $"seed {Seed(G)}");+ Learn(seedTb, PSeed, "Seed");+ var rerollBtn = Button("Reroll", "Next seed — a new roll", Reroll, out _);+ var lockBtn = Button("Lock", "Hold the roll showing now — it repeats every bar", ToggleLock, out var lockSync);+ Learn(lockBtn, PLocked, "Locked");+ readouts.Add(() => lockSync(Locked(G)));+ var seedRow = new DockPanel { Children =+ {+ WithDock(new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Children = { rerollBtn, lockBtn } }, Dock.Right),+ seedTb,+ } };++ var scaleRow = SwitchRow(PStayInScale, "Stay in scale · C maj", "Snap every varied note into C major");++ var dice = new DockPanel { Margin = new Thickness(8, 6), Children =+ {+ WithDock(new StackPanel { Spacing = 5, Children = { chanceRow, distSeg } }, Dock.Top),+ WithDock(new StackPanel { Spacing = 5, Margin = new Thickness(0, 5, 0, 0), Children = { rateSeg, seedRow, scaleRow } }, Dock.Bottom),+ new Border { Margin = new Thickness(0, 5, 0, 0), Child = histBox },+ } };+ var diceIsland = IslandBox(IslandHead(Caps("DICE"), null), dice, 160);++ varyIsland.Margin = new Thickness(0, 0, 5, 0); diceIsland.Margin = new Thickness(5, 0, 0, 0);+ var islands = new DockPanel { Children = { WithDock(varyIsland, Dock.Left), WithDock(diceIsland, Dock.Right), outIsland } };++ var statusL = new TextBlock { FontSize = 8, Foreground = Sub, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };+ var statusR = Mono("", Sub);+ readouts.Add(() =>+ {+ statusL.Text = $"Chance {ChanceText(G(PChance))} · {Dists[Dist(G)]} · {(G(PRate) >= 0.5f ? "per bar" : "per note")} · seed {Seed(G)}"+ + (Locked(G) ? " locked" : "") + (G(PStayInScale) >= 0.5f ? " · C maj" : "");+ statusR.Text = Bypassed() ? "bypassed" : "MIDI · latency 0 smp";+ });+ 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);+ // Distribution chip: click for the next, Shift-click for the previous.+ var distTb = new TextBlock { FontSize = 9, Foreground = Txt, VerticalAlignment = VerticalAlignment.Center };+ var chev = new Glyph(GlyphKind.ChevronDown, 7) { Foreground = Cap, VerticalAlignment = VerticalAlignment.Center };+ var distChip = new Border { Height = 14, Width = 62, CornerRadius = NotaRadius.Badge, Background = NotaPalette.GridBeat, BorderBrush = Bd, BorderThickness = new Thickness(1),+ Padding = new Thickness(6, 0), Cursor = new Cursor(StandardCursorType.Hand),+ Child = new DockPanel { Children = { WithDock(chev, Dock.Right), distTb } } };+ distChip.PointerPressed += (_, ev) =>+ {+ if (!ev.GetCurrentPoint(distChip).Properties.IsLeftButtonPressed) return;+ int d = ev.KeyModifiers.HasFlag(KeyModifiers.Shift) ? 2 : 1;+ Set(PDist, (Dist(G) + d) % 3); Refresh(); ev.Handled = true;+ };+ ToolTip.SetTip(distChip, "Distribution: Gauss / Even / Walk — click for the next, Shift-click for the previous");+ Learn(distChip, PDist, "Dist");+ var barTb = Mono("", Cap, 7);+ var head = new DockPanel { Height = 14, Children = { WithDock(distChip, Dock.Left), WithDock(barTb, Dock.Right) } };+ barTb.HorizontalAlignment = HorizontalAlignment.Right;++ var viz = new RandomOutputViz { Full = false };+ ToolTip.SetTip(viz, "Dashed — in · filled — out (brightness = velocity) · × — skipped");++ var knobs = new Grid { Height = 53, ColumnDefinitions = new ColumnDefinitions("*,*,*,*") };+ var cells = new[]+ {+ KnobCell("CHANCE", PChance, 1, ChanceText),+ KnobCell("NOTE", PNoteRange, 12, NoteText),+ KnobCell("VEL", PVelAmt, 1, VelText),+ KnobCell("TIME", PTimeAmt, 1, TimeText),+ };+ 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), new Border { Margin = new Thickness(0, 4), Child = viz },+ } };+ 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(() =>+ {+ distTb.Text = Dists[Dist(G)];+ barTb.Text = $"bar {ShownBar() + 1}" + (Locked(G) ? " · held" : "");+ viz.Set(notes, now, Bypassed());+ });++ // Footer: "seed N" rerolls, "lock" holds the roll.+ var seedTb = FooterLink("", "Reroll — the next seed", Reroll);+ Learn(seedTb, PSeed, "Seed");+ var lockTb = FooterLink("", "Lock — hold the roll showing now", ToggleLock, mono: false);+ Learn(lockTb, PLocked, "Locked");+ var left = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Children = { seedTb, lockTb } };+ var statusR = Mono("", Sub);+ readouts.Add(() =>+ {+ seedTb.Text = $"seed {Seed(G)}";+ bool on = Locked(G);+ lockTb.Text = on ? "locked" : "lock";+ lockTb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;+ lockTb.Tag = on ? NotaPalette.AccentHover : Sub;+ if (!lockTb.IsPointerOver) lockTb.Foreground = (IBrush)lockTb.Tag;+ statusR.Text = Bypassed() ? "bypassed" : $"{Changed()} changed · {Skipped()} skip";+ });+ return Framed(island, left, statusR);+ }++ // ---- shared pieces -----------------------------------------------------------------------+ Control Framed(Control main, Control left, TextBlock right)+ {+ 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 } } };+ }++ Control IslandHead(Control left, Control? right)+ {+ 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)+ {+ 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;+ }++ Control LegendItem(Control swatch, string text)+ {+ swatch.VerticalAlignment = VerticalAlignment.Center;+ return new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, Children =+ { swatch, new TextBlock { Text = text, FontSize = 7, Foreground = Muted, VerticalAlignment = VerticalAlignment.Center } } };+ }++ // A plain amount slider (0..max), automation-bracketed; double-click resets.+ SliderTrack Slider(int p, double max)+ {+ var trk = new SliderTrack { Height = 11, Reset = () => { Set(p, Def(p)); Refresh(); } };+ bool stepped = max > 1;+ trk.Changed += n => { S(p, stepped ? Math.Round(n * max) : Math.Round(n * max, 3)); Refresh(); };+ trk.GestureBegin += () => Begin(p);+ trk.GestureEnd += () => End(p);+ Learn(trk, p, engine.MidiEffectParamName(track, mi, p));+ readouts.Add(() => { if (!trk.Dragging) trk.Norm = G(p) / max; });+ return trk;+ }++ // One WHAT VARIES row: the label (lit once it does something), the value (brass once moved+ // off the default) and the amount slider under them.+ Control VaryRow(string label, int p, double max, Func<double, string> fmt, string tip)+ {+ var l = new TextBlock { Text = label, FontSize = 9, VerticalAlignment = VerticalAlignment.Center };+ var v = Mono("", Sub); v.HorizontalAlignment = HorizontalAlignment.Right;+ var trk = Slider(p, max);+ ToolTip.SetTip(trk, $"{tip} — drag up / down, double-click resets");+ readouts.Add(() =>+ {+ double x = G(p);+ l.Foreground = x > 0.0005 ? Txt : Cap;+ v.Foreground = Math.Abs(x - Def(p)) > 0.0005 ? BrassLit : Sub;+ v.Text = fmt(x);+ });+ return new StackPanel { Spacing = 2, VerticalAlignment = VerticalAlignment.Center, Children =+ {+ new DockPanel { Children = { WithDock(v, Dock.Right), l } }, trk,+ } };+ }++ Control Seg(int p, string[] names, string tip)+ {+ var seg = DeviceCardKit.Segments(names, () => Math.Clamp((int)Math.Round(G(p)), 0, names.Length - 1),+ i => { Set(p, i); Refresh(); }, out var sync, fill: true, padX: 2, fontSize: 8);readouts.Add(sync);- MidiLearn.Bind(seg, MidiTarget.MidiDeviceParam(track, mi, p), engine.MidiEffectParamName(track, mi, p));+ Learn(seg, p, engine.MidiEffectParamName(track, mi, p));+ ToolTip.SetTip(seg, tip);return seg;}- Control Toggle(int p, string label, IBrush accent)++ // A small action button (Reroll / Lock); the sync paints the engaged (brass-wash) state.+ Border Button(string text, string tip, Action click, out Action<bool> sync){- var host = DeviceCardKit.Switch(label, () => G(p) >= 0.5f, () => { S(p, G(p) >= 0.5f ? 0 : 1); Refresh(); }, out var sync);- readouts.Add(sync);- MidiLearn.Bind(host, MidiTarget.MidiDeviceParam(track, mi, p), label);- return host;- }- // One "what varies" row: name · amount bar (category colour) · range text.- Control VaryRow(string name, int p, double min, double max, Func<double, string> fmt, IBrush colour)- {- var nm = new TextBlock { Text = name, FontSize = 9, Foreground = Txt, Width = 56, VerticalAlignment = VerticalAlignment.Center };- var val = Mono(fmt(G(p)), Sub); val.Width = 46; val.TextAlignment = TextAlignment.Right;- var fill = new Border { Background = colour, CornerRadius = NotaRadius.Badge, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Stretch };- var slot = new Panel { Height = 9, Cursor = new Cursor(StandardCursorType.Hand), Background = Inset };- slot.Children.Add(fill);- var slotClip = new Border { Height = 9, CornerRadius = NotaRadius.Badge, ClipToBounds = true, Child = slot, VerticalAlignment = VerticalAlignment.Center };- void Vis(double v) { fill.Width = (v - min) / (max - min) * slot.Bounds.Width; }- bool drag = false;- void SetX(double x) { double n = Math.Clamp(x / Math.Max(1, slot.Bounds.Width), 0, 1); double v = min + n * (max - min); S(p, v); Vis(v); val.Text = fmt(v); Refresh(); }- slot.PointerPressed += (_, e) => { drag = true; e.Pointer.Capture(slot); SetX(e.GetPosition(slot).X); };- slot.PointerMoved += (_, e) => { if (drag) SetX(e.GetPosition(slot).X); };- slot.PointerReleased += (_, e) => { if (drag) { drag = false; e.Pointer.Capture(null); } };- MidiLearn.Bind(slot, MidiTarget.MidiDeviceParam(track, mi, p), engine.MidiEffectParamName(track, mi, p));- slot.SizeChanged += (_, _) => Vis(G(p));- readouts.Add(() => { if (!drag) { Vis(G(p)); val.Text = fmt(G(p)); } });- var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 7, VerticalAlignment = VerticalAlignment.Center };- Grid.SetColumn(slotClip, 1); Grid.SetColumn(val, 2);- g.Children.Add(nm); g.Children.Add(slotClip); g.Children.Add(val);- return new Border { Height = 26, Child = g };- }-- // ---- LIVE strip ----- var chance = MiniSlider("CHANCE", PChance, 0, 1, v => $"{v * 100:0}\u2009%", 110);- var distSeg = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = { Cap("DIST"), Seg(PDist, Dists) } };- var seedTxt = Mono("", Teal, 9);- readouts.Add(() => seedTxt.Text = $"seed {Gi(PSeed)}" + (G(PLocked) >= 0.5f ? " · locked" : ""));- var lockBtn = new Border { CornerRadius = NotaRadius.Control, BorderThickness = new Thickness(1), Padding = new Thickness(8, 2), Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = "Lock seed", FontSize = 9 } };- void LockSync() { bool on = G(PLocked) >= 0.5f; lockBtn.Background = on ? NotaPalette.AccentSubtle : Card; lockBtn.BorderBrush = on ? NotaPalette.BorderBrass : Bd; ((TextBlock)lockBtn.Child!).Foreground = on ? NotaPalette.AccentHover : Sub; }- lockBtn.PointerPressed += (_, _) => { S(PLocked, G(PLocked) >= 0.5f ? 0 : 1); Refresh(); };- readouts.Add(LockSync); LockSync();- var reroll = new Border { Background = Card, BorderBrush = Bd, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(8, 2), Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = "Re-roll", FontSize = 9, Foreground = Sub } };- reroll.PointerPressed += (_, _) => { long s = (long)Gi(PSeed); s = (s * 1103515245L + 12345L) % 1000L; if (s <= 0) s += 1000; S(PSeed, s); Refresh(); };- var liveR = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Right, Children = { seedTxt, lockBtn, reroll } };- var liveL = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center, Children = { chance, distSeg } };- var liveGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };- Grid.SetColumn(liveR, 1); liveGrid.Children.Add(liveL); liveGrid.Children.Add(liveR);- var liveStrip = new Border { Height = 34, Background = HdrBg, BorderBrush = Bd, BorderThickness = new Thickness(0, 0, 0, 1), Padding = new Thickness(9, 0), Child = liveGrid };-- // ---- WHAT VARIES ----- var vHead = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), Height = 11 };- var vh1 = Cap("amount · range"); vh1.HorizontalAlignment = HorizontalAlignment.Right; Grid.SetColumn(vh1, 1);- vHead.Children.Add(Cap("WHAT VARIES")); vHead.Children.Add(vh1);- var varyStack = new StackPanel { Spacing = 3, Children =- {- vHead,- VaryRow("Note", PNoteRange, 0, 12, v => v < 0.5 ? "off" : $"±{v:0}\u2009st", Amber),- VaryRow("Velocity", PVelAmt, 0, 1, v => v < 0.01 ? "off" : $"±{v * 0.5 * 127:0}", Amber),- VaryRow("Timing", PTimeAmt, 0, 1, v => v < 0.01 ? "off" : $"±{v * 50:0}\u2009ms", Teal),- VaryRow("Skip", PSkip, 0, 1, v => v < 0.01 ? "off" : $"{v * 100:0}\u2009%", Red),- VaryRow("Octave", POctAmt, 0, 1, v => { int n = (int)Math.Round(v * 2); return n <= 0 ? "off" : $"±{n}\u2009oct"; }, Amber),- } };- var varyPanel = new Border { Padding = new Thickness(8, 6), Child = varyStack };-- // ---- DISTRIBUTION rail ----- var distViz = new DistributionViz { Height = 56 };- distViz.Set(Gi(PDist));- readouts.Add(() => distViz.Set(Gi(PDist)));- var distAxis = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto") };- var da1 = Mono("centre", Muted, 8); da1.HorizontalAlignment = HorizontalAlignment.Center;- var da2 = Mono("+max", NotaPalette.TextDisabled, 8); da2.HorizontalAlignment = HorizontalAlignment.Right;- Grid.SetColumn(da1, 1); Grid.SetColumn(da2, 2);- distAxis.Children.Add(Mono("−max", NotaPalette.TextDisabled, 8)); distAxis.Children.Add(da1); distAxis.Children.Add(da2);- var rateRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = { Cap("RATE"), Seg(PRate, Rates, null, 8, 8) } };- var railStack = new StackPanel { Spacing = 5, Children =- {- Cap("DISTRIBUTION"), distViz, distAxis,- new Border { Height = 1, Background = Card, Margin = new Thickness(0, 1) },- rateRow, Toggle(PStayInScale, "STAY IN SCALE", Teal),- } };- var rail = new Border { Width = 210, Background = RailBg, BorderBrush = Bd, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(8, 6), Child = railStack };-- var body = new DockPanel { LastChildFill = true };- DockPanel.SetDock(rail, Dock.Right); body.Children.Add(rail); body.Children.Add(varyPanel);- var root = new DockPanel { LastChildFill = true, Background = NotaPalette.BgApp };- DockPanel.SetDock(liveStrip, Dock.Top); root.Children.Add(liveStrip); root.Children.Add(body);+ var tb = new TextBlock { Text = text, FontSize = 8, Foreground = Txt, VerticalAlignment = VerticalAlignment.Center };+ var b = new Border { Height = 16, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Padding = new Thickness(6, 0),+ Background = NotaPalette.TrackOff, BorderBrush = NotaPalette.TrackOff, Cursor = new Cursor(StandardCursorType.Hand), Child = tb };+ bool engaged = false;+ b.PointerEntered += (_, _) => { if (!engaged) b.Background = NotaPalette.SurfaceHover; };+ b.PointerExited += (_, _) => { if (!engaged) b.Background = NotaPalette.TrackOff; };+ b.PointerPressed += (_, ev) =>+ {+ if (!ev.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return;+ click(); ev.Handled = true;+ };+ ToolTip.SetTip(b, tip);+ sync = on =>+ {+ engaged = on;+ b.Background = on ? NotaPalette.AccentSubtle : b.IsPointerOver ? NotaPalette.SurfaceHover : NotaPalette.TrackOff;+ b.BorderBrush = on ? NotaPalette.BorderBrass : NotaPalette.TrackOff;+ tb.Foreground = on ? NotaPalette.AccentHover : Txt;+ tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;+ };+ return b;+ }- Refresh();- return root;+ // A switch + sentence-case label (Stay in scale).+ Control SwitchRow(int p, string label, string tip)+ {+ var sw = new SwitchTrack { VerticalAlignment = VerticalAlignment.Center };+ var tb = new TextBlock { Text = label, FontSize = 8, VerticalAlignment = VerticalAlignment.Center };+ var row = new Border { Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand),+ Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Children = { sw, tb } } };+ row.PointerPressed += (_, ev) =>+ {+ if (!ev.GetCurrentPoint(row).Properties.IsLeftButtonPressed) return;+ Set(p, G(p) >= 0.5f ? 0 : 1); Refresh(); ev.Handled = true;+ };+ ToolTip.SetTip(row, tip);+ Learn(row, p, label);+ readouts.Add(() => { bool on = G(p) >= 0.5f; sw.IsOn = on; tb.Foreground = on ? Txt : Muted; });+ return row;+ }++ // A clickable footer word (mini view): Ink 3, primary on hover.+ TextBlock FooterLink(string text, string tip, Action click, bool mono = true)+ {+ var tb = mono ? Mono(text, Sub) : new TextBlock { Text = text, FontSize = 8, Foreground = Sub, VerticalAlignment = VerticalAlignment.Center };+ tb.Tag = Sub;+ tb.Cursor = new Cursor(StandardCursorType.Hand); tb.Background = Brushes.Transparent;+ tb.PointerEntered += (_, _) => tb.Foreground = Txt;+ tb.PointerExited += (_, _) => tb.Foreground = (IBrush)tb.Tag!;+ tb.PointerPressed += (_, ev) =>+ {+ if (!ev.GetCurrentPoint(tb).Properties.IsLeftButtonPressed) return;+ click(); ev.Handled = true;+ };+ ToolTip.SetTip(tb, tip);+ return tb;+ }++ // A mini-view knob: 34px gauge, caps label, mono value.+ Control KnobCell(string label, int p, double max, Func<double, string> text)+ {+ var knob = new Knob(G(p) / max, 1.0) { Accent = true, Width = 34, Height = 34, HorizontalAlignment = HorizontalAlignment.Center, Default = Def(p) / max };+ knob.ValueChanged += n => { S(p, max > 1 ? Math.Round(n * max) : Math.Round(n * max, 3)); Refresh(); };+ knob.GestureBegin += () => Begin(p);+ knob.GestureEnd += () => End(p);+ Learn(knob, p, label);+ var v = Mono("", Sub, 7); v.HorizontalAlignment = HorizontalAlignment.Center;+ readouts.Add(() => { double n = G(p) / max; if (!knob.Dragging && Math.Abs(knob.Value - n) > 1e-6) knob.Value = n; v.Text = text(G(p)); });+ return new StackPanel { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Cursor = new Cursor(StandardCursorType.SizeNorthSouth),+ Children = { knob, new TextBlock { Text = label, FontSize = 7, FontWeight = FontWeight.Bold, LetterSpacing = 0.6, Foreground = Cap, HorizontalAlignment = HorizontalAlignment.Center, LineHeight = 9 }, v } };+ }}}diff --git a/src/managed/Nota.App/DeviceCards/Midi/ScaleMidiBody.cs b/src/managed/Nota.App/DeviceCards/Midi/ScaleMidiBody.csindex c8c48608..90161107 100644--- a/src/managed/Nota.App/DeviceCards/Midi/ScaleMidiBody.cs+++ b/src/managed/Nota.App/DeviceCards/Midi/ScaleMidiBody.cs@@ -1,18 +1,25 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Detail · Devices — the Nota Scale editor (MIDI effect kind 2), mockup 3b (700×260 on the-// shared shell): a LIVE strip (Root stepper · scale-type presets · Fold mode) over a body of-// an interactive NOTE MAP (the 12 pitch classes; click to add/remove one from the scale;-// out-of-scale notes show the arrow to where they fold) beside a right rail (live IN→OUT of-// the last remapped note, Range limiter, Follow Key, Learn/Clear).+// Detail · Devices — the Nota Scale editor (MIDI effect kind 2), 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 — ROOT stepper over the scale TYPE list (Major / Minor / Dorian / Phryg /+// Penta / Custom, each with its note count) | NOTE MAP: the twelve pitch classes as key+// cells — scale notes Brass Deep, the root edged Brass Light, the rest naming where they+// fold; click one to add / remove it (the scale turns Custom) | FOLD: Nearest / Down / Up,+// the last IN → OUT, Range (± an octave, drag for semitones), Follow key, Learn and Clear —+// over a status line.+// • S 260 × 260 — root stepper, type and fold on one row, the note map, IN → OUT. Range,+// Follow key, Learn and Clear are L-only (presets still set them); the header keeps the+// same preset picker as L.+// The note sounding now lights its cell and fades after release (engine telemetry, so even a+// note shorter than a frame flashes); the cell it folded onto gets a fainter ring.using System;using System.Collections.Generic;-using System.Linq;using Avalonia;using Avalonia.Controls;-using Avalonia.Controls.Shapes;using Avalonia.Input;using Avalonia.Layout;using Avalonia.Media;@@ -23,193 +30,469 @@ namespace Nota.App;internal sealed class ScaleMidiBody : IMidiDeviceBody{// Param indices — mirror MidiScale.h.- private const int PRoot = 0, PScale = 1, PMask0 = 3, PFold = 15, PFollowKey = 16, PRangeLo = 17, PRangeHi = 18, PLearn = 19;- private const int Custom = 10;+ internal const int PRoot = 0, PScale = 1, PTranspose = 2, PMask0 = 3, PFold = 15, PFollowKey = 16,+ PRangeLo = 17, PRangeHi = 18, PLearn = 19, PView = 20, Custom = 10;private static readonly string[] Notes = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };- // Chip label → Scale param value (preset index, or Custom).- private static readonly (string name, int idx)[] Chips = { ("Major", 0), ("Minor", 1), ("Dorian", 3), ("Phryg", 4), ("Penta", 8), ("Custom", Custom) };- private static readonly int[] PresetMasks = { 2741, 1453, 2477, 1709, 1451, 2773, 1717, 661, 1193, 4095 };+ // Every Scale value's name (0..9 presets, 10 Custom) and mask (bits relative to the root).+ internal static readonly string[] ScaleNames = { "Major", "Minor", "Harm Minor", "Dorian", "Phryg", "Lydian", "Mixolyd", "Penta", "Penta Min", "Chromatic", "Custom" };+ internal static readonly int[] PresetMasks = { 2741, 1453, 2477, 1709, 1451, 2773, 1717, 661, 1193, 4095 };+ // The TYPE list of the mockup → Scale value. The last row is Custom (or names an unlisted preset).+ private static readonly int[] TypeRows = { 0, 1, 3, 4, 7, Custom };private static readonly string[] Folds = { "Nearest", "Down", "Up" };- private static readonly IBrush HdrBg = NotaPalette.SurfaceCard;+ 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 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 Green = NotaPalette.Success;- private static readonly IBrush Card = NotaPalette.SurfaceRaised;- private static readonly IBrush Ink = NotaPalette.TextOnAccent;- private static readonly IBrush AmberSubtle = NotaPalette.Wash(NotaPalette.Accent, 0x28);+ private static readonly IBrush Muted = NotaPalette.TextMuted;+ private static readonly IBrush Cap = NotaPalette.TextTertiary;+ private static readonly IBrush Axis = NotaPalette.TextAxis;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;++ // ---- the scale model (mirrors MidiScale.h) -------------------------------------------------+ internal static int RootOf(Func<int, float> g) => (((int)Math.Round(g(PRoot))) % 12 + 12) % 12;+ internal static int ScaleOf(Func<int, float> g) => Math.Clamp((int)Math.Round(g(PScale)), 0, Custom);+ internal static int MaskOf(Func<int, float> g)+ {+ int sc = ScaleOf(g);+ if (sc < Custom) return PresetMasks[sc];+ int m = 0; for (int i = 0; i < 12; i++) if (g(PMask0 + i) >= 0.5f) m |= 1 << i;+ return m;+ }+ internal static int Count(int mask) { int n = 0; for (int i = 0; i < 12; i++) n += mask >> i & 1; return n; }+ internal static string KeyTag(Func<int, float> g) => $"{Notes[RootOf(g)]} {ScaleNames[ScaleOf(g)]}";++ 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 = KeyTag(p => e.MidiEffectGetParam(t, index, p)).ToUpperInvariant();+ Sync();+ ctx.AddDeviceRefresher(Sync);+ ToolTip.SetTip(tag, "The key in effect: root and scale");+ 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 Scale", Margin = new Thickness(8) };float G(int p) => engine.MidiEffectGetParam(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 Set(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);+ bool mini = IsMini(engine, track, mi);var readouts = new List<Action>();- 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; }- 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 string NoteName(int pitch) => Notes[((pitch % 12) + 12) % 12] + (pitch / 12 - 2); // C3 = 60void Refresh() { foreach (var r in readouts) r(); }- int Root() => Math.Clamp(Gi(PRoot), 0, 11);- int Mask()- {- int sc = Gi(PScale);- if (sc < Custom) return PresetMasks[Math.Clamp(sc, 0, 9)];- int m = 0; for (int i = 0; i < 12; i++) if (G(PMask0 + i) >= 0.5f) m |= 1 << i;- return m;- }- // Ensure the mask is editable: copy the effective preset mask into Mask params + switch to Custom.+ int Root() => RootOf(G);+ int Sc() => ScaleOf(G);+ int Mask() => MaskOf(G);+ int Fold() => Math.Clamp((int)Math.Round(G(PFold)), 0, 2);+ string TypeName() => ScaleNames[Sc()];+ int Remapped() => Mask() == 0 ? 0 : 12 - Count(Mask());++ // Editing the notes needs the mask in the Mask params: copy a preset's there and go Custom.void MakeCustom(){- if (Gi(PScale) >= Custom) return;+ if (Sc() >= Custom) return;int m = Mask();- for (int i = 0; i < 12; i++) S(PMask0 + i, (m >> i) & 1);- S(PScale, Custom);+ for (int i = 0; i < 12; i++) Set(PMask0 + i, (m >> i) & 1);+ Set(PScale, Custom);}- bool InScale(int absPc) => (Mask() & (1 << (((absPc - Root()) % 12 + 12) % 12))) != 0;- int SnapRel(int rel, int mask, int fold)+ void PickType(int sc) { if (sc == Custom) MakeCustom(); else Set(PScale, sc); Refresh(); }+ void ToggleNote(int pc)+ {+ MakeCustom();+ int rel = ((pc - Root()) % 12 + 12) % 12;+ Set(PMask0 + rel, G(PMask0 + rel) >= 0.5f ? 0 : 1);+ Refresh();+ }+ void StepRoot(int d) { Set(PRoot, ((Root() + d) % 12 + 12) % 12); Refresh(); }+ // Clear leaves the root alone in a Custom scale — build up from there, or Learn.+ void Clear() { for (int i = 0; i < 12; i++) Set(PMask0 + i, i == 0 ? 1 : 0); Set(PScale, Custom); Refresh(); }++ // ---- live telemetry: IN → OUT and the note-map animation ------------------------------------+ var scope = new float[32];+ var lastIn = new int[12]; var lastOut = new int[12]; bool primed = false;+ int li = -1, lo = -1;+ var map = new ScaleNoteMap { Mini = mini };+ map.Toggled += ToggleNote;+ ToolTip.SetTip(map, "Click a note to add it to or take it out of the scale (the scale turns Custom)");+ void Poll(){- bool Has(int x) => (mask & (1 << (((x % 12) + 12) % 12))) != 0;- if (Has(rel)) return ((rel % 12) + 12) % 12;- if (fold == 1) { for (int d = 1; d < 12; d++) if (Has(rel - d)) return ((rel - d) % 12 + 12) % 12; }- else if (fold == 2) { for (int d = 1; d < 12; d++) if (Has(rel + d)) return (rel + d) % 12; }- else { for (int d = 1; d < 7; d++) { if (Has(rel + d)) return (rel + d) % 12; if (Has(rel - d)) return ((rel - d) % 12 + 12) % 12; } }- return ((rel % 12) + 12) % 12;+ int n = engine.MidiEffectScope(track, mi, scope);+ bool by = Bypassed();+ li = n >= 2 && !by ? (int)scope[0] : -1;+ lo = n >= 2 && !by ? (int)scope[1] : -1;+ int heldIn = 0, heldOut = 0, hitIn = 0, hitOut = 0;+ if (n >= 32)+ {+ for (int pc = 0; pc < 12; pc++)+ {+ int ci = (int)scope[8 + pc], co = (int)scope[20 + pc];+ if (primed && ci != lastIn[pc]) hitIn |= 1 << pc;+ if (primed && co != lastOut[pc]) hitOut |= 1 << pc;+ lastIn[pc] = ci; lastOut[pc] = co;+ }+ primed = true;+ heldIn = (int)scope[4]; heldOut = (int)scope[5];+ }+ if (by) heldIn = heldOut = hitIn = hitOut = 0;+ map.Animate(heldIn, heldOut, hitIn, hitOut);}+ readouts.Add(() => map.SetScale(Root(), Mask(), Fold()));++ Poll();+ Control rootView = mini ? BuildMini() : BuildLarge();+ ctx.AddDeviceRefresher(() => { Poll(); Refresh(); });+ Refresh();+ return rootView;- // ---- generic controls ----- Control Seg(int p, string[] names, Action<int>? extra = null)+ // =========================================================================================+ Control BuildLarge(){- var seg = DeviceCardKit.Segments(names, () => Math.Clamp(Gi(p), 0, names.Length - 1), iv => { S(p, iv); extra?.Invoke(iv); Refresh(); }, out var sync);+ // ---- ROOT + TYPE ----+ var list = new StackPanel { Margin = new Thickness(0, 3) };+ for (int i = 0; i < TypeRows.Length; i++)+ {+ int sc = TypeRows[i];+ bool last = i == TypeRows.Length - 1;+ bool On() => last ? Array.IndexOf(TypeRows, Sc()) < 0 || Sc() == Custom : Sc() == sc;+ var bar = new Border { Width = 2, Margin = new Thickness(0, 3), HorizontalAlignment = HorizontalAlignment.Left };+ var name = new TextBlock { Text = ScaleNames[sc], FontSize = 9, VerticalAlignment = VerticalAlignment.Center };+ var count = Mono("", Axis, 7); count.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(count, Dock.Right), name } } } } };+ bool hover = false;+ void Paint()+ {+ bool on = On();+ 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;+ // The Custom row names an unlisted preset scale when one is in effect (Lydian …).+ if (last) name.Text = on ? TypeName() : "Custom";+ count.Text = (last ? (on ? Count(Mask()) : Count(CustomMask())) : Count(PresetMasks[sc])).ToString();+ }+ int CustomMask() { int m = 0; for (int k = 0; k < 12; k++) if (G(PMask0 + k) >= 0.5f) m |= 1 << k; return m; }+ rowB.PointerEntered += (_, _) => { hover = true; Paint(); };+ rowB.PointerExited += (_, _) => { hover = false; Paint(); };+ rowB.PointerPressed += (_, ev) =>+ {+ if (!ev.GetCurrentPoint(rowB).Properties.IsLeftButtonPressed) return;+ PickType(last ? Custom : sc); ev.Handled = true;+ };+ ToolTip.SetTip(rowB, last ? "Custom: your own notes — click the note map to edit" : $"{ScaleNames[sc]} — {Count(PresetMasks[sc])} notes");+ Learn(rowB, PScale, "Scale");+ readouts.Add(Paint);+ list.Children.Add(rowB);+ }+ var typeIsland = IslandBox(IslandHead(Caps("ROOT"), RootStepper()), list, 100);++ // ---- NOTE MAP ----+ var remapped = Mono("", Cap, 7);+ readouts.Add(() => remapped.Text = Mask() == 0 ? "empty · notes pass" : $"{Remapped()} of 12 remapped");+ var mapIsland = IslandBox(IslandHead(Caps("NOTE MAP"), remapped), new Border { Padding = new Thickness(8, 6), Child = map }, double.NaN);++ // ---- FOLD ----+ var foldSeg = FoldSeg(13);+ var ioIn = Mono("—", Sub, 13); var ioOut = Mono("—", BrassLit, 13);+ var ioBox = new Border+ {+ Height = 30, Background = Well, BorderBrush = Rule, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge,+ Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Center,+ Children = { ioIn, new TextBlock { Text = "→", FontSize = 10, Foreground = Cap, VerticalAlignment = VerticalAlignment.Center }, ioOut } },+ };+ ToolTip.SetTip(ioBox, "The last note played and what it came out as");+ readouts.Add(() => { ioIn.Text = li >= 0 ? DeviceCardKit.NoteName(li) : "—"; ioOut.Text = lo >= 0 ? DeviceCardKit.NoteName(lo) : "—"; });+ var io = new StackPanel { Spacing = 3, Children = { Caps("LAST IN → OUT"), ioBox } };++ var rangeLbl = Caps("RANGE"); rangeLbl.Width = 34;+ var range = new Grid { ColumnDefinitions = new ColumnDefinitions("34,*,*"), ColumnSpacing = 6 };+ var rLo = RangeBox(PRangeLo, "Range low"); var rHi = RangeBox(PRangeHi, "Range high");+ Grid.SetColumn(rLo, 1); Grid.SetColumn(rHi, 2);+ range.Children.Add(rangeLbl); range.Children.Add(rLo); range.Children.Add(rHi);++ var follow = FollowSwitch();+ var learnBtn = LearnButton();+ var clearBtn = Button("Clear", Clear, "Clear the scale down to the root (Custom)");+ var btns = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 4 };+ Grid.SetColumn(clearBtn, 1); btns.Children.Add(learnBtn); btns.Children.Add(clearBtn);++ var foldBody = new DockPanel { Margin = new Thickness(8, 6), Children =+ {+ WithDock(btns, Dock.Bottom),+ new StackPanel { Spacing = 7, Children = { foldSeg, io, range, follow } },+ } };+ var foldIsland = IslandBox(IslandHead(Caps("FOLD"), null), foldBody, 160);++ typeIsland.Margin = new Thickness(0, 0, 5, 0); foldIsland.Margin = new Thickness(5, 0, 0, 0);+ var islands = new DockPanel { Children = { WithDock(typeIsland, Dock.Left), WithDock(foldIsland, Dock.Right), mapIsland } };++ var statusL = new TextBlock { FontSize = 8, Foreground = Sub, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };+ var statusR = Mono("", Sub);+ readouts.Add(() =>+ {+ int t = (int)Math.Round(G(PTranspose));+ statusL.Text = $"{Notes[Root()]} {TypeName()} · {Count(Mask())} notes · fold {Folds[Fold()].ToLowerInvariant()} · "+ + $"{DeviceCardKit.NoteName(RangeLo())}–{DeviceCardKit.NoteName(RangeHi())}"+ + (t != 0 ? $" · transpose {(t > 0 ? "+" : "−")}{Math.Abs(t)}" : "")+ + (G(PFollowKey) >= 0.5f ? " · follow key" : "")+ + (G(PLearn) >= 0.5f ? " · learning" : "");+ statusR.Text = Bypassed() ? "bypassed" : "MIDI · latency 0 smp";+ });+ return Framed(islands, statusL, statusR);+ }++ // =========================================================================================+ Control BuildMini()+ {+ var top = new DockPanel { Children = { WithDock(RootStepper(), Dock.Left), WithDock(TypeDrop(), Dock.Left), FoldSeg(12) } };+ ((Control)top.Children[1]).Margin = new Thickness(5, 0);++ var ioIn = Mono("—", Sub, 11); var ioOut = Mono("—", BrassLit, 11);+ var ioBar = new Border+ {+ Height = 24, Background = Well, BorderBrush = Rule, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(8, 0),+ Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, Children =+ { Mono("IN → OUT", Cap, 7), ioIn, new TextBlock { Text = "→", FontSize = 9, Foreground = Cap, VerticalAlignment = VerticalAlignment.Center }, ioOut } },+ };+ readouts.Add(() => { ioIn.Text = li >= 0 ? DeviceCardKit.NoteName(li) : "—"; ioOut.Text = lo >= 0 ? DeviceCardKit.NoteName(lo) : "—"; });++ var inner = new DockPanel { Children =+ {+ WithDock(top, Dock.Top), WithDock(ioBar, Dock.Bottom), new Border { Margin = new Thickness(0, 6), Child = map },+ } };+ var island = new Border { Background = Island, BorderBrush = Bd, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile,+ Padding = new Thickness(6), Child = inner };++ var statusL = new TextBlock { FontSize = 8, Foreground = Sub, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };+ var statusR = Mono("", Sub);+ readouts.Add(() =>+ {+ statusL.Text = $"{Notes[Root()]} {TypeName()} · {Count(Mask())} notes";+ statusR.Text = Bypassed() ? "bypassed" : Mask() == 0 ? "empty" : $"{Remapped()} of 12 remapped";+ });+ return Framed(island, statusL, statusR);+ }++ // ---- shared pieces -----------------------------------------------------------------------+ int RangeLo() => Math.Clamp((int)Math.Round(G(PRangeLo)), 0, 127);+ int RangeHi() => Math.Clamp((int)Math.Round(G(PRangeHi)), 0, 127);++ Control Framed(Control main, TextBlock left, TextBlock right)+ {+ 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 } } };+ }++ Control IslandHead(Control left, Control? right)+ {+ var d = new DockPanel { Margin = new Thickness(8, 0, right is null ? 8 : 4, 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)+ {+ 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;+ }++ Border Chip(Control child, double w, double h = 14)+ {+ return new Border { Width = w, Height = h, CornerRadius = NotaRadius.Badge, Background = NotaPalette.TrackOff, Cursor = new Cursor(StandardCursorType.Hand),+ VerticalAlignment = VerticalAlignment.Center, Child = child };+ }++ // ‹ C › — click to step, scroll too. Follow key moves it on its own.+ Control RootStepper()+ {+ Border Arrow(GlyphKind glyph, int d)+ {+ var b = Chip(new Glyph(glyph, 7) { Foreground = Sub, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }, 14);+ b.PointerPressed += (_, ev) => { if (!ev.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; StepRoot(d); ev.Handled = true; };+ b.PointerEntered += (_, _) => b.Background = NotaPalette.SurfaceHover;+ b.PointerExited += (_, _) => b.Background = NotaPalette.TrackOff;+ return b;+ }+ var name = Mono("", BrassLit, 9); name.FontWeight = FontWeight.SemiBold; name.Width = 20; name.TextAlignment = TextAlignment.Center;+ readouts.Add(() => name.Text = Notes[Root()]);+ var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2, VerticalAlignment = VerticalAlignment.Center, Background = Brushes.Transparent,+ Children = { Arrow(GlyphKind.ChevronLeft, -1), name, Arrow(GlyphKind.ChevronRight, 1) } };+ row.PointerWheelChanged += (_, ev) => { StepRoot(ev.Delta.Y > 0 ? 1 : -1); ev.Handled = true; };+ ToolTip.SetTip(row, "Root — click the arrows or scroll");+ Learn(row, PRoot, "Root");+ return row;+ }++ Control FoldSeg(double h)+ {+ var seg = DeviceCardKit.Segments(Folds, Fold, i => { Set(PFold, i); Refresh(); }, out var sync, fill: true, padX: 2, fontSize: 8);+ seg.Height = h + 4;readouts.Add(sync);- MidiLearn.Bind(seg, MidiTarget.MidiDeviceParam(track, mi, p), engine.MidiEffectParamName(track, mi, p));+ ToolTip.SetTip(seg, "Fold — where an out-of-scale note goes: the nearest scale note (a tie goes up), the one below or the one above");+ Learn(seg, PFold, "Fold");return seg;}- Control Toggle(int p, string label, IBrush accent)++ // The mini card's scale type: a dropdown (scroll steps through the list).+ Control TypeDrop(){- var host = DeviceCardKit.Switch(label, () => G(p) >= 0.5f, () => { S(p, G(p) >= 0.5f ? 0 : 1); Refresh(); }, out var sync);- readouts.Add(sync);- MidiLearn.Bind(host, MidiTarget.MidiDeviceParam(track, mi, p), label);- return host;+ var name = new TextBlock { FontSize = 9, Foreground = Txt, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };+ var box = new Border+ {+ Width = 54, Height = 16, Background = NotaPalette.GridBeat, BorderBrush = Bd, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge,+ Padding = new Thickness(6, 0), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center,+ Child = new DockPanel { Children = { WithDock(new Glyph(GlyphKind.ChevronDown, 7) { Foreground = Cap, VerticalAlignment = VerticalAlignment.Center }, Dock.Right), name } },+ };+ readouts.Add(() => name.Text = TypeName());+ box.PointerPressed += (_, ev) =>+ {+ if (!ev.GetCurrentPoint(box).Properties.IsLeftButtonPressed) return;+ var fly = new MenuFlyout();+ foreach (int sc in TypeRows)+ {+ int iv = sc;+ var item = new MenuItem { Header = ScaleNames[sc] };+ if (Sc() == sc) item.Icon = new Avalonia.Controls.Shapes.Ellipse { Width = 6, Height = 6, Fill = NotaPalette.Accent };+ item.Click += (_, _) => PickType(iv);+ fly.Items.Add(item);+ }+ fly.ShowAt(box);+ ev.Handled = true;+ };+ box.PointerWheelChanged += (_, ev) =>+ {+ int at = Array.IndexOf(TypeRows, Sc()); if (at < 0) at = TypeRows.Length - 1;+ PickType(TypeRows[Math.Clamp(at + (ev.Delta.Y < 0 ? 1 : -1), 0, TypeRows.Length - 1)]); ev.Handled = true;+ };+ ToolTip.SetTip(box, "Scale type");+ Learn(box, PScale, "Scale");+ return box;}- Control Btn(string label, Action onClick)++ // − C-1 + : an octave per click; drag the note up / down for semitones; double-click resets.+ Control RangeBox(int p, string label){- var b = new Border { Background = Card, BorderBrush = Bd, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(0, 3), HorizontalAlignment = HorizontalAlignment.Stretch, Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = label, FontSize = 9, Foreground = Sub, HorizontalAlignment = HorizontalAlignment.Center } };- b.PointerPressed += (_, _) => { onClick(); Refresh(); };- return b;+ int Get() => p == PRangeLo ? RangeLo() : RangeHi();+ void Put(int v)+ {+ v = p == PRangeLo ? Math.Clamp(v, 0, RangeHi()) : Math.Clamp(v, RangeLo(), 127);+ S(p, v); Refresh();+ }+ TextBlock Sign(string s) => new() { Text = s, Width = 12, FontSize = 9, Foreground = Muted, TextAlignment = TextAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ var dec = new Border { Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Child = Sign("−") };+ var inc = new Border { Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Child = Sign("+") };+ var val = Mono("", Txt, 8); val.TextAlignment = TextAlignment.Center; val.HorizontalAlignment = HorizontalAlignment.Stretch;+ var valHit = new Border { Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.SizeNorthSouth), Child = val };+ dec.PointerPressed += (_, ev) => { if (!ev.GetCurrentPoint(dec).Properties.IsLeftButtonPressed) return; Begin(p); Put(Get() - 12); End(p); ev.Handled = true; };+ inc.PointerPressed += (_, ev) => { if (!ev.GetCurrentPoint(inc).Properties.IsLeftButtonPressed) return; Begin(p); Put(Get() + 12); End(p); ev.Handled = true; };+ bool drag = false; double y0 = 0; int v0 = 0;+ valHit.PointerPressed += (_, ev) =>+ {+ if (!ev.GetCurrentPoint(valHit).Properties.IsLeftButtonPressed) return;+ ev.Handled = true;+ if (ev.ClickCount == 2) { Begin(p); Put(p == PRangeLo ? 0 : 127); End(p); return; }+ drag = true; y0 = ev.GetPosition(valHit).Y; v0 = Get(); ev.Pointer.Capture(valHit); Begin(p);+ };+ valHit.PointerMoved += (_, ev) => { if (drag) Put(v0 + (int)Math.Round((y0 - ev.GetPosition(valHit).Y) / 4)); };+ void Stop() { if (!drag) return; drag = false; End(p); }+ valHit.PointerReleased += (_, ev) => { if (drag) ev.Pointer.Capture(null); Stop(); };+ valHit.PointerCaptureLost += (_, _) => Stop();+ valHit.PointerWheelChanged += (_, ev) => { Begin(p); Put(Get() + (ev.Delta.Y > 0 ? 1 : -1)); End(p); ev.Handled = true; };+ readouts.Add(() => val.Text = DeviceCardKit.NoteName(Get()));+ var box = new Border+ {+ Height = 14, Background = Well, BorderBrush = Bd, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge,+ Child = new DockPanel { Children = { WithDock(dec, Dock.Left), WithDock(inc, Dock.Right), valHit } },+ };+ ToolTip.SetTip(box, $"{label} — ± an octave, drag or scroll the note for semitones, double-click resets. Notes outside the range pass through.");+ Learn(box, p, label);+ return box;}- Control PitchDrag(int p, double w) // vertical-drag MIDI pitch shown as a note name++ Control FollowSwitch(){- var tb = Mono(NoteName(Gi(p)), Txt); tb.Width = w; tb.Cursor = new Cursor(StandardCursorType.SizeNorthSouth); tb.TextAlignment = TextAlignment.Center;- bool drag = false; double sy = 0, sv = 0;- tb.PointerPressed += (_, e) => { drag = true; sy = e.GetPosition(tb).Y; sv = G(p); e.Pointer.Capture(tb); };- tb.PointerMoved += (_, e) => { if (drag) { double dv = (sy - e.GetPosition(tb).Y) / 6.0; S(p, Math.Clamp(sv + dv, 0, 127)); tb.Text = NoteName(Gi(p)); } };- tb.PointerReleased += (_, e) => { if (drag) { drag = false; e.Pointer.Capture(null); } };- MidiLearn.Bind(tb, MidiTarget.MidiDeviceParam(track, mi, p), engine.MidiEffectParamName(track, mi, p));- readouts.Add(() => { if (!drag) tb.Text = NoteName(Gi(p)); });- return tb;+ var sw = new SwitchTrack { Width = SwitchTrack.W, Height = SwitchTrack.H, VerticalAlignment = VerticalAlignment.Center };+ var lbl = new TextBlock { Text = "Follow key · from input", FontSize = 8, VerticalAlignment = VerticalAlignment.Center };+ var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Children = { sw, lbl } };+ row.PointerPressed += (_, ev) =>+ {+ if (!ev.GetCurrentPoint(row).Properties.IsLeftButtonPressed) return;+ Set(PFollowKey, G(PFollowKey) >= 0.5f ? 0 : 1); Refresh(); ev.Handled = true;+ };+ readouts.Add(() => { bool on = G(PFollowKey) >= 0.5f; sw.IsOn = on; lbl.Foreground = on ? Txt : Muted; });+ ToolTip.SetTip(row, "Follow key — the root moves to the key that best fits what you play (keeping the scale type)");+ Learn(row, PFollowKey, "Follow Key");+ return row;}- // ---- LIVE strip ----- var rootName = Mono("C", Txt); rootName.Width = 20; rootName.TextAlignment = TextAlignment.Center;- Border StepBtn(GlyphKind t, int dir)+ Border Button(string text, Action click, string tip){- var b = new Border { Width = 16, CornerRadius = NotaRadius.Badge, BorderBrush = Bd, BorderThickness = new Thickness(1), Background = Card, Cursor = new Cursor(StandardCursorType.Hand), Child = new Glyph(t, 8) { Foreground = Sub }, VerticalAlignment = VerticalAlignment.Center };- b.PointerPressed += (_, _) => { S(PRoot, ((Root() + dir) % 12 + 12) % 12); Refresh(); };+ var tb = new TextBlock { Text = text, FontSize = 8, Foreground = Txt, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ var b = new Border { Height = 16, CornerRadius = NotaRadius.Badge, Background = NotaPalette.TrackOff, BorderBrush = NotaPalette.TrackOff, BorderThickness = new Thickness(1),+ Cursor = new Cursor(StandardCursorType.Hand), Child = tb };+ b.PointerEntered += (_, _) => { if (b.Tag is null) b.Background = NotaPalette.SurfaceHover; };+ b.PointerExited += (_, _) => { if (b.Tag is null) b.Background = NotaPalette.TrackOff; };+ b.PointerPressed += (_, ev) => { if (!ev.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return; click(); ev.Handled = true; };+ ToolTip.SetTip(b, tip);return b;}- readouts.Add(() => rootName.Text = Notes[Root()]);- var rootStepper = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3, VerticalAlignment = VerticalAlignment.Center, Children = { Cap("ROOT"), StepBtn(GlyphKind.ChevronLeft, -1), rootName, StepBtn(GlyphKind.ChevronRight, +1) } };-- // scale chips (highlight the preset matching PScale, or Custom)- var chipArr = new Border[Chips.Length];- void ChipsHi() { int sc = Gi(PScale); for (int i = 0; i < Chips.Length; i++) { bool on = Chips[i].idx == sc || (sc >= Custom && Chips[i].idx == Custom); chipArr[i].Background = on ? Amber : Brushes.Transparent; ((TextBlock)chipArr[i].Child!).Foreground = on ? Ink : Muted; } }- var chipRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 1 };- for (int i = 0; i < Chips.Length; i++) { int iv = i; var c = new Border { CornerRadius = NotaRadius.Badge, Padding = new Thickness(7, 1), Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = Chips[i].name, FontSize = 9, Foreground = Muted } }; c.PointerPressed += (_, _) => { S(PScale, Chips[iv].idx); Refresh(); }; chipArr[i] = c; chipRow.Children.Add(c); }- readouts.Add(ChipsHi); ChipsHi();- var scaleChips = new Border { Background = Inset, BorderBrush = Bd, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(1), VerticalAlignment = VerticalAlignment.Center, Child = chipRow };-- var foldSeg = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Right, Children = { Cap("FOLD"), Seg(PFold, Folds) } };- var liveL = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center, Children = { rootStepper, scaleChips } };- var liveGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };- Grid.SetColumn(foldSeg, 1); liveGrid.Children.Add(liveL); liveGrid.Children.Add(foldSeg);- var liveStrip = new Border { Height = 34, Background = HdrBg, BorderBrush = Bd, BorderThickness = new Thickness(0, 0, 0, 1), Padding = new Thickness(9, 0), Child = liveGrid };-- // ---- NOTE MAP (6×2 pitch classes) ----- var remapped = Cap("", Muted); remapped.HorizontalAlignment = HorizontalAlignment.Right;- var mapHead = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), Height = 11 };- Grid.SetColumn(remapped, 1); mapHead.Children.Add(Cap("NOTE MAP")); mapHead.Children.Add(remapped);- var grid = new Grid { VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Stretch };- for (int c = 0; c < 6; c++) grid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));- for (int r = 0; r < 2; r++) grid.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));- for (int pc = 0; pc < 12; pc++)- {- int iv = pc;- var nlbl = new TextBlock { Text = Notes[pc], FontSize = 9, FontWeight = FontWeight.SemiBold, HorizontalAlignment = HorizontalAlignment.Center };- var arrow = Mono("", Teal, 8); arrow.HorizontalAlignment = HorizontalAlignment.Center;- var cell = new Border { Margin = new Thickness(2), CornerRadius = NotaRadius.Control, BorderThickness = new Thickness(1), Cursor = new Cursor(StandardCursorType.Hand), Child = new StackPanel { VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center, Spacing = 1, Children = { nlbl, arrow } } };- cell.PointerPressed += (_, _) => { MakeCustom(); int rel = ((iv - Root()) % 12 + 12) % 12; S(PMask0 + rel, (G(PMask0 + rel) >= 0.5f) ? 0 : 1); Refresh(); };++ // Learn is a mode: "Learning…" while it collects the notes you play into a fresh Custom scale.+ Control LearnButton()+ {+ var b = Button("Learn", () => { Set(PLearn, G(PLearn) >= 0.5f ? 0 : 1); Refresh(); },+ "Learn — play the notes of your scale; they pass through untouched and become the Custom scale. Click again to finish.");+ var tb = (TextBlock)b.Child!;readouts.Add(() =>{- bool inScale = InScale(iv), isRoot = iv == Root();- cell.Background = inScale ? AmberSubtle : Inset;- cell.BorderBrush = isRoot ? Green : inScale ? Amber : Bd;- nlbl.Foreground = inScale ? Txt : Muted;- if (inScale) { arrow.Text = isRoot ? "root" : "•"; arrow.Foreground = isRoot ? Green : Amber; }- else { int rel = ((iv - Root()) % 12 + 12) % 12; int tgt = (SnapRel(rel, Mask(), Math.Clamp(Gi(PFold), 0, 2)) + Root()) % 12; arrow.Text = "→ " + Notes[tgt]; arrow.Foreground = Teal; }+ bool on = G(PLearn) >= 0.5f;+ b.Tag = on ? "on" : null;+ b.Background = on ? NotaPalette.AccentSubtle : b.IsPointerOver ? NotaPalette.SurfaceHover : NotaPalette.TrackOff;+ b.BorderBrush = on ? NotaPalette.BorderBrass : NotaPalette.TrackOff;+ tb.Foreground = on ? NotaPalette.AccentHover : Txt;+ tb.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;+ tb.Text = on ? "Learning…" : "Learn";});- Grid.SetColumn(cell, pc % 6); Grid.SetRow(cell, pc / 6); grid.Children.Add(cell);- }- var mapDock = new DockPanel { LastChildFill = true };- DockPanel.SetDock(mapHead, Dock.Top); mapDock.Children.Add(mapHead); mapDock.Children.Add(new Border { Margin = new Thickness(0, 4, 0, 0), Child = grid });-- // ---- right rail ----- var inTxt = Mono("—", Sub, 11); var arrTxt = new TextBlock { Text = "→", FontSize = 9, Foreground = Teal, VerticalAlignment = VerticalAlignment.Center };- var outTxt = Mono("—", AmberLit, 11); var distTxt = Mono("", Muted, 8); distTxt.HorizontalAlignment = HorizontalAlignment.Right;- var ioInner = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,*") };- var ioCells = new Control[] { inTxt, arrTxt, outTxt, distTxt };- for (int c = 0; c < ioCells.Length; c++) { Grid.SetColumn(ioCells[c], c); ((Control)ioCells[c]).Margin = new Thickness(c == 0 ? 0 : 4, 0, 0, 0); ioInner.Children.Add(ioCells[c]); }- var ioBox = new Border { Background = Inset, BorderBrush = Bd, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(7, 5), Child = ioInner };- readouts.Add(() =>- {- int li = engine.MidiEffectLastIn(track, mi), lo = engine.MidiEffectLastOut(track, mi);- if (li < 0) { inTxt.Text = "—"; outTxt.Text = "—"; distTxt.Text = ""; }- else { inTxt.Text = NoteName(li); outTxt.Text = NoteName(lo); int d = lo - li; distTxt.Text = d == 0 ? "0" : (d > 0 ? "+" : "−") + Math.Abs(d) + "\u2009st"; }- });- var rangeRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, VerticalAlignment = VerticalAlignment.Center, Children = { Cap("RANGE"), PitchDrag(PRangeLo, 30), new TextBlock { Text = "–", FontSize = 9, Foreground = Muted, VerticalAlignment = VerticalAlignment.Center }, PitchDrag(PRangeHi, 30) } };- var followKey = Toggle(PFollowKey, "FOLLOW KEY", Teal);- var learnBtn = Btn("Learn", () => S(PLearn, 1));- var clearBtn = Btn("Clear", () => { for (int i = 0; i < 12; i++) S(PMask0 + i, 0); S(PScale, Custom); });- var btnRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 4 };- Grid.SetColumn(clearBtn, 1); btnRow.Children.Add(learnBtn); btnRow.Children.Add(clearBtn);- var railStack = new StackPanel { Spacing = 6, Children = { Cap("LAST IN → OUT"), ioBox, rangeRow, followKey } };- var railDock = new DockPanel { LastChildFill = false, VerticalAlignment = VerticalAlignment.Stretch };- DockPanel.SetDock(railStack, Dock.Top); DockPanel.SetDock(btnRow, Dock.Bottom);- railDock.Children.Add(railStack); railDock.Children.Add(btnRow);- var rail = new Border { Width = 150, BorderBrush = Bd, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(9, 0, 0, 0), Child = railDock };-- // remapped count in the note-map header- readouts.Add(() => { int m = Mask(); int inN = 0; for (int i = 0; i < 12; i++) if ((m & (1 << i)) != 0) inN++; remapped.Text = $"{12 - inN} of 12 remapped"; });-- var body = new DockPanel { LastChildFill = true, Margin = new Thickness(9, 7) };- DockPanel.SetDock(rail, Dock.Right); body.Children.Add(rail); body.Children.Add(mapDock);- var root = new DockPanel { LastChildFill = true, Background = NotaPalette.BgApp };- DockPanel.SetDock(liveStrip, Dock.Top); root.Children.Add(liveStrip); root.Children.Add(body);-- ctx.AddDeviceRefresher(Refresh); // live IN→OUT + Follow-Key / Learn feedback- Refresh();- return root;+ Learn(b, PLearn, "Learn");+ return b;+ }}}diff --git a/src/managed/Nota.App/DeviceChainView.Shell.cs b/src/managed/Nota.App/DeviceChainView.Shell.csindex 0f474d18..9e40eab4 100644--- a/src/managed/Nota.App/DeviceChainView.Shell.cs+++ b/src/managed/Nota.App/DeviceChainView.Shell.cs@@ -120,7 +120,7 @@ public sealed partial class DeviceChainViewVerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis,};- var right = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center };+ var right = new StackPanel { Orientation = Orientation.Horizontal, Spacing = s.Compact ? 6 : 8, HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center };// Type badge (mono caps). An instrument that reports its voices shows them here, live,// as the badge's value — e.g. "SYNTH · 3/16".@@ -205,7 +205,7 @@ public sealed partial class DeviceChainView// A compact (mini) card keeps the same picker — same list, same current preset — only narrower:// the preset belongs to the device, not to the card size.if (presets.Count > 0) right.Children.Insert(0, PresetPicker(presets.Select(p => p.Name).ToList(), curPreset, extra.Preset, ApplyPreset, StepPreset,- nameWidth: s.Compact ? 78 : 132));+ nameWidth: s.Compact ? 74 : 132));void Move(int to) { if (s.Kind == ChainKind.Midi) _engine.MoveMidiEffect(_trackId, di, to); else _engine.MoveDevice(_trackId, di, to); ExtrasMoved(s.Kind, di, to); Rebuild(); Changed?.Invoke(); }diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.csindex 554a9921..8fd1006d 100644--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs@@ -2198,25 +2198,121 @@ public sealed class FactoryPresetCatalog : IFactoryPresetsChord("Sub Octave", new[] { -12 });Chord("Soft Fifth + Oct", new[] { 7, 12 }, vel: new[] { -20, -35 });Chord("Tone Cluster", new[] { 1, 2, 3 }, vel: new[] { -10, -15, -20 });- // ---- Nota Scale (MIDI, kind 2) — Root 0..11, Scale 0..9 preset / 10 Custom; Fold 0 Near/1 Down/2 Up- Midi("scale", 2, "C Minor", ("Root", 0f), ("Scale", 1f));- Midi("scale", 2, "Penta Minor", ("Root", 0f), ("Scale", 8f), ("Fold", 1f));- Midi("scale", 2, "Dorian Up", ("Root", 0f), ("Scale", 3f), ("Fold", 2f));- // ---- Nota Length (MIDI, kind 3) — Mode 0 Sync/1 ms/2 Gate%; Rate 0 1/16..3 1/4- Midi("notelength", 3, "Staccato", ("Mode", 0f), ("Rate", 0f), ("Gate", 1f));- Midi("notelength", 3, "Tenuto 1/4", ("Mode", 0f), ("Rate", 3f), ("Gate", 1f));- Midi("notelength", 3, "Half Gate", ("Mode", 2f), ("Percent", 50f));- Midi("notelength", 3, "Fixed 120ms", ("Mode", 1f), ("Ms", 120f));+ // ---- Nota Scale (MIDI, kind 2) — almanac rework. Root 0 C … 11 B; Scale 0 Major / 1 Minor /+ // 2 Harm Minor / 3 Dorian / 4 Phrygian / 5 Lydian / 6 Mixolydian / 7 Penta / 8 Penta Minor /+ // 9 Chromatic, or a Custom set of degrees (semitones above the root); Fold 0 Nearest /+ // 1 Down / 2 Up; Range as MIDI notes (outside passes through); Transpose ±24 st.+ Scl("Init", root: 0, scale: 1);+ Scl("C Major", root: 0, scale: 0);+ Scl("A Minor", root: 9, scale: 1);+ Scl("E Minor Down", root: 4, scale: 1, fold: 1);+ Scl("G Major Up", root: 7, scale: 0, fold: 2);+ Scl("D Dorian", root: 2, scale: 3);+ Scl("E Phrygian", root: 4, scale: 4);+ Scl("F Lydian", root: 5, scale: 5);+ Scl("G Mixolydian", root: 7, scale: 6);+ Scl("A Harmonic Minor", root: 9, scale: 2);+ Scl("C Penta", root: 0, scale: 7);+ Scl("A Penta Minor", root: 9, scale: 8, fold: 1);+ Scl("Black Keys (F# Penta)", root: 6, scale: 7);+ Scl("White Keys Only", root: 0, scale: 0, fold: 1);+ Scl("A Blues", root: 9, degrees: new[] { 0, 3, 5, 6, 7, 10 });+ Scl("C Melodic Minor", root: 0, degrees: new[] { 0, 2, 3, 5, 7, 9, 11 });+ Scl("E Phrygian Dominant", root: 4, degrees: new[] { 0, 1, 4, 5, 7, 8, 10 });+ Scl("D Hijaz", root: 2, degrees: new[] { 0, 1, 4, 5, 7, 8, 10 }, fold: 1);+ Scl("C Double Harmonic", root: 0, degrees: new[] { 0, 1, 4, 5, 7, 8, 11 });+ Scl("A Hirajoshi", root: 9, degrees: new[] { 0, 2, 3, 7, 8 });+ Scl("E In Sen", root: 4, degrees: new[] { 0, 1, 5, 7, 10 });+ Scl("C Whole Tone", root: 0, degrees: new[] { 0, 2, 4, 6, 8, 10 });+ Scl("C Diminished", root: 0, degrees: new[] { 0, 2, 3, 5, 6, 8, 9, 11 });+ Scl("B Locrian", root: 11, degrees: new[] { 0, 1, 3, 5, 6, 8, 10 });+ Scl("C Major Triad", root: 0, degrees: new[] { 0, 4, 7 });+ Scl("A Minor Triad", root: 9, degrees: new[] { 0, 3, 7 }, fold: 1);+ Scl("Root + Fifth", root: 0, degrees: new[] { 0, 7 }, fold: 1);+ Scl("Octaves Only", root: 0, degrees: new[] { 0 }, fold: 1);+ Scl("Bass Line C Minor", root: 0, scale: 1, fold: 1, lo: 24, hi: 59);+ Scl("Lead Above C4", root: 0, scale: 0, lo: 60, hi: 127);+ Scl("Up a Fifth, Major", root: 0, scale: 0, transpose: 7);+ Scl("Octave Down, Minor", root: 0, scale: 1, transpose: -12);+ Scl("Follow Key Major", root: 0, scale: 0, follow: true);+ Scl("Follow Key Minor", root: 9, scale: 1, follow: true);+ Scl("Chromatic Pass", root: 0, scale: 9);+ // ---- Nota Length (MIDI, kind 3) — almanac rework. Mode 0 Sync / 1 ms / 2 Gate %;+ // Division 0 1/32 · 1 1/16 · 2 1/8 · 3 1/4 · 4 1/2 · 5 1/1 · 6 1/8. · 7 1/4T; Trigger 0 from+ // note-on / 1 from note-off; Vel / Key to Len −1..+1 (+ = loud / low notes longer).+ Len("Staccato", mode: 0, div: 1);+ Len("Eighths", mode: 0, div: 2);+ Len("Tenuto 1/4", mode: 0, div: 3);+ Len("Half Notes", mode: 0, div: 4);+ Len("Whole Bar", mode: 0, div: 5, clip: true);+ Len("Dotted Eighth", mode: 0, div: 6);+ Len("Quarter Triplet", mode: 0, div: 7);+ Len("32nd Blips", mode: 0, div: 0);+ Len("Blip 40ms", mode: 1, ms: 40);+ Len("Fixed 120ms", mode: 1, ms: 120);+ Len("Fixed 250ms", mode: 1, ms: 250);+ Len("Fixed 500ms", mode: 1, ms: 500);+ Len("One Second", mode: 1, ms: 1000, clip: true);+ Len("Half Gate", mode: 2, pct: 50);+ Len("Tight Quarter Gate", mode: 2, pct: 25);+ Len("Almost Legato", mode: 2, pct: 90);+ Len("Stretch 150%", mode: 2, pct: 150);+ Len("Double Gate", mode: 2, pct: 200, clip: true);+ Len("Release Echo", mode: 0, div: 1, trig: 1);+ Len("Off-Beat Ghost", mode: 1, ms: 80, trig: 1, vel: -0.3f);+ Len("Release Swell", mode: 2, pct: 100, trig: 1, clip: true);+ Len("Dynamic Length", mode: 0, div: 2, vel: 0.8f);+ Len("Soft Tails", mode: 0, div: 3, vel: -0.6f);+ Len("Bass Heavy", mode: 0, div: 2, key: 0.7f);+ Len("Bright Tops", mode: 0, div: 3, key: -0.6f);+ Len("Humanized", mode: 0, div: 2, rnd: 0.3f);+ Len("Loose Hands", mode: 2, pct: 90, vel: 0.3f, rnd: 0.2f);+ Len("Chaos Gate", mode: 1, ms: 300, rnd: 0.8f);+ Len("Pluck Machine", mode: 1, ms: 40, vel: 0.5f, key: 0.3f);+ 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 = linearMidi("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 Random (MIDI, kind 5) — Dist 0 Gauss/1 Even/2 Walk; Rate 0 note/1 bar- Midi("random", 5, "Human Drift", ("Chance", 0.7f), ("Note Range", 1f), ("Time Amt", 0.3f), ("Vel Amt", 0.3f), ("Dist", 2f));- Midi("random", 5, "Pitch Roulette",("Chance", 0.5f), ("Note Range", 12f), ("Dist", 1f), ("Stay In Scale", 1f));- Midi("random", 5, "Ghost Notes", ("Chance", 1f), ("Note Range", 0f), ("Skip", 0.35f), ("Vel Amt", 0.4f));- Midi("random", 5, "Octave Jumps", ("Chance", 0.4f), ("Note Range", 0f), ("Oct Amt", 0.5f), ("Rate", 1f));+ // ---- 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+ // same roll repeats every bar.+ Rnd("Init", chance: 0.5f, note: 7);+ Rnd("Human Touch", chance: 1f, vel: 0.2f, time: 0.1f);+ Rnd("Loose Drummer", chance: 1f, vel: 0.35f, time: 0.2f, skip: 0.05f);+ Rnd("Tight Humanize", chance: 1f, vel: 0.12f, time: 0.05f);+ Rnd("Lazy Behind", chance: 0.8f, time: 0.45f, dist: 2);+ Rnd("Velocity Shimmer", chance: 1f, vel: 0.5f, dist: 1);+ Rnd("Accent Lottery", chance: 0.3f, vel: 0.8f, dist: 1);+ Rnd("Ghost Notes", chance: 1f, vel: 0.4f, skip: 0.35f);+ Rnd("Sparse Hats", chance: 1f, skip: 0.5f, vel: 0.25f, dist: 1);+ Rnd("Thin Out", chance: 1f, skip: 0.2f);+ Rnd("Stutter Drop", chance: 0.6f, skip: 0.6f, time: 0.15f, dist: 1);+ Rnd("Pitch Roulette", chance: 0.5f, note: 12, dist: 1, scale: true);+ Rnd("Gentle Wander", chance: 0.6f, note: 2, scale: true);+ Rnd("Melodic Drift", chance: 0.8f, note: 5, dist: 2, scale: true);+ Rnd("Wide Leaps", chance: 0.5f, note: 12, dist: 1);+ Rnd("Chromatic Smear", chance: 0.4f, note: 1, dist: 1);+ Rnd("Neighbour Tones", chance: 0.35f, note: 2, scale: true, dist: 1);+ Rnd("Octave Jumps", chance: 0.4f, oct: 0.5f, rate: 1);+ Rnd("Octave Scatter", chance: 0.6f, oct: 1f, dist: 1);+ Rnd("Sub Drops", chance: 0.3f, oct: 0.5f, vel: 0.2f);+ Rnd("Bar Transposer", chance: 1f, note: 5, rate: 1, dist: 1, scale: true);+ Rnd("Bar Mood", chance: 1f, vel: 0.4f, time: 0.2f, rate: 1, dist: 2);+ Rnd("Random Walk Bass", chance: 1f, note: 4, dist: 2, scale: true);+ Rnd("Walking Octaves", chance: 0.7f, note: 3, oct: 0.5f, dist: 2, scale: true);+ Rnd("Generative Keys", chance: 0.7f, note: 7, vel: 0.3f, time: 0.1f, skip: 0.15f, dist: 2, scale: true);+ Rnd("Glitch Machine", chance: 0.8f, note: 12, vel: 0.6f, time: 0.3f, skip: 0.3f, oct: 0.5f, dist: 1);+ Rnd("Chaos", chance: 1f, note: 12, vel: 1f, time: 0.6f, skip: 0.4f, oct: 1f, dist: 1);+ Rnd("Subtle Chaos", chance: 0.25f, note: 3, vel: 0.2f, time: 0.1f, skip: 0.1f);+ Rnd("Frozen Variation", chance: 0.6f, note: 5, vel: 0.3f, skip: 0.15f, scale: true, seed: 7);+ Rnd("Frozen Groove", chance: 1f, vel: 0.4f, time: 0.25f, skip: 0.2f, seed: 42);+ Rnd("Frozen Arp Shuffle", chance: 0.7f, note: 7, oct: 0.5f, dist: 1, scale: true, seed: 128);+ Rnd("Frozen Melody", chance: 0.9f, note: 5, dist: 2, scale: true, seed: 311);}public IReadOnlyList<FactoryPresetInfo> All()@@ -2398,6 +2494,18 @@ public sealed class FactoryPresetCatalog : IFactoryPresetsFx("eq", 0, name, ps.ToArray());}+ // A Nota Scale preset: a preset scale (0..9) or a Custom set of degrees above the root.+ private void Scl(string name, int root, int scale = 10, int[]? degrees = null, int fold = 0, int lo = 0, int hi = 127,+ int transpose = 0, bool follow = false)+ {+ var ps = new List<(string, float)> { ("Root", root), ("Scale", degrees is null ? scale : 10), ("Fold", fold),+ ("Range Low", lo), ("Range High", hi), ("Transpose", transpose), ("Follow Key", follow ? 1 : 0) };+ // The Custom notes: the listed degrees, or (for a preset scale) the major default.+ int[] mask = degrees ?? new[] { 0, 2, 4, 5, 7, 9, 11 };+ for (int d = 0; d < 12; d++) ps.Add(($"Mask {d}", System.Array.IndexOf(mask, d) >= 0 ? 1 : 0));+ Midi("scale", 2, name, ps.ToArray());+ }+// A Nota Chord preset: every slot is written (shifts listed in order are switched on, the rest off).private void Chord(string name, int[] shifts, float strum = 0, float spread = 0, bool keepRoot = true, bool fold = false,int key = 0, bool minor = false, int[]? vel = null)@@ -2428,6 +2536,26 @@ public sealed class FactoryPresetCatalog : IFactoryPresetsMidi("arp", 0, name, ps.ToArray());}+ // A Nota Length preset (MIDI kind 3); every sound param is named so switching presets is exact.+ private void Len(string name, int mode, int div = 2, float ms = 250, float pct = 100, int trig = 0,+ float vel = 0, float key = 0, float rnd = 0, bool legato = false, bool clip = false)+ => 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 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,+ int dist = 0, int rate = 0, bool scale = false, int seed = 0)+ {+ var ps = new List<(string, float)>+ {+ ("Chance", chance), ("Note Range", note), ("Vel Amt", vel), ("Time Amt", time), ("Skip", skip), ("Oct Amt", oct),+ ("Dist", dist), ("Rate", rate), ("Stay In Scale", scale ? 1 : 0), ("Locked", seed > 0 ? 1 : 0),+ };+ if (seed > 0) { ps.Add(("Seed", seed)); ps.Add(("Lock Bar", 0)); }+ Midi("random", 5, name, ps.ToArray());+ }+private void Midi(string group, int kind, string name, params (string Name, float Value)[] ps)=> Add(group, name, "builtin-midi-effect", kind, isInstrument: false, isMidi: true, ps);diff --git a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs b/src/managed/Nota.Infrastructure/Persistence/PresetService.csindex 663de523..9d09e45a 100644--- a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs+++ b/src/managed/Nota.Infrastructure/Persistence/PresetService.cs@@ -136,6 +136,18 @@ public static class PresetServiceengine.MidiEffectSetParam(trackId, index, 16 + v, Math.Abs(engine.MidiEffectGetParam(trackId, index, v)) >= 0.5f ? 1f : 0f);}+ /// <summary>Nota Length (MIDI kind 3) before the almanac rework: four sync rates in Rate+ /// (1/16 · 1/8 · 1/8D · 1/4) — now Division (8 values) — and a Key to Len where + made HIGH+ /// notes longer (now + makes low notes longer). Maps both onto the new params.</summary>+ public static void LengthLegacy(IAudioEngine engine, int trackId, int index)+ {+ if (engine.MidiEffectParamCount(trackId, index) < 12) return;+ int[] rateToDivision = { 1, 2, 6, 3 };+ int rate = Math.Clamp((int)Math.Round(engine.MidiEffectGetParam(trackId, index, 0)), 0, 3);+ engine.MidiEffectSetParam(trackId, index, 11, rateToDivision[rate]);+ engine.MidiEffectSetParam(trackId, index, 7, -engine.MidiEffectGetParam(trackId, index, 7));+ }+private static void LegacyRange(PresetDocument doc, IAudioEngine engine, int trackId, int deviceIndex){if (doc.BuiltinKind != 16 || engine.DeviceParamCount(trackId, deviceIndex) <= 10) return;@@ -177,6 +189,7 @@ public static class PresetServiceif (doc.NamedParams.TryGetValue(engine.MidiEffectParamName(targetTrackId, mi, i), out var v))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);}return "";}@@ -299,6 +312,9 @@ public static class PresetService// A Nota Chord preset saved before its slots had switches: "0 semitones" meant off.if (engine.MidiEffectKind(trackId, deviceIndex) == 1 && !doc.NamedParams.ContainsKey("On 1"))ChordLegacySwitches(engine, trackId, deviceIndex);+ // 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);}return "";}diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.csindex 8256cec1..e87b7b8d 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs@@ -606,6 +606,7 @@ public sealed class ProjectServiceint mpc = engine.MidiEffectParamCount(id, mi);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 Lengthif (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.csindex 2e702a40..9ae28717 100644--- a/src/managed/Nota.Mcp/Tools/MidiFxTools.cs+++ b/src/managed/Nota.Mcp/Tools/MidiFxTools.cs@@ -272,4 +272,315 @@ public sealed class MidiFxTools(IAudioEngine engine, IEngineDispatch dispatch, Iif (on is { } o) S(COn + s, o ? 1 : 0);if (velocity is { } v) S(CVel + s, Math.Clamp(v, -64, 63));});++ // ---- Nota Scale (kind 2) — named access ---------------------------------------------------+ // Param layout mirrors MidiScale.h: Root 0, Scale 1, Transpose 2, Mask 0..11 = 3..14, Fold 15,+ // Follow Key 16, Range Low 17, Range High 18, Learn 19, View 20.+ private const int SRoot = 0, SScale = 1, STrans = 2, SMask = 3, SFold = 15, SFollow = 16, SLo = 17, SHi = 18, SLearn = 19, SView = 20, SCustom = 10;+ private static readonly string[] ScaleIds = { "major", "minor", "harmonic-minor", "dorian", "phrygian", "lydian", "mixolydian", "penta", "penta-minor", "chromatic", "custom" };+ private static readonly int[] ScaleMasks = { 2741, 1453, 2477, 1709, 1451, 2773, 1717, 661, 1193, 4095 };+ private static readonly string[] ScaleFolds = { "nearest", "down", "up" };+ private static readonly string[] PcNames = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };++ public sealed record ScaleState(+ string Root, string Scale, int[] Degrees, string[] Notes, string Fold, int Transpose, int RangeLow, int RangeHigh,+ bool FollowKey, bool Learning, string View, int LastIn, int LastOut, string[] FoldMap, int[] HeldPitchClasses);++ private void RequireScale(int trackId, int index)+ {+ if (E.MidiEffectKind(trackId, index) != 2 || E.MidiEffectParamCount(trackId, index) <= SView)+ throw new ArgumentException($"MIDI effect {index} on track {trackId} is not a Nota Scale.");+ }+ private static int ParsePc(string s)+ {+ string t = s.Trim().Replace("♯", "#").Replace("♭", "b");+ int i = Array.FindIndex(PcNames, x => string.Equals(x, t, StringComparison.OrdinalIgnoreCase));+ if (i >= 0) return i;+ string[] flats = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };+ i = Array.FindIndex(flats, x => string.Equals(x, t, StringComparison.OrdinalIgnoreCase));+ if (i >= 0) return i;+ throw new ArgumentException($"Unknown note '{s}'. Use C, C#/Db … B.");+ }+ private int ScaleMask(int trackId, int index)+ {+ int sc = Math.Clamp((int)MathF.Round(E.MidiEffectGetParam(trackId, index, SScale)), 0, SCustom);+ if (sc < SCustom) return ScaleMasks[sc];+ int m = 0; for (int i = 0; i < 12; i++) if (E.MidiEffectGetParam(trackId, index, SMask + i) >= 0.5f) m |= 1 << i;+ return m;+ }+ // Put the scale in effect into the Mask params and switch to Custom, so single notes can be edited.+ private void ScaleMakeCustom(int trackId, int index)+ {+ if ((int)MathF.Round(E.MidiEffectGetParam(trackId, index, SScale)) >= SCustom) return;+ int m = ScaleMask(trackId, index);+ for (int i = 0; i < 12; i++) E.MidiEffectSetParam(trackId, index, SMask + i, (m >> i) & 1);+ E.MidiEffectSetParam(trackId, index, SScale, SCustom);+ }++ [McpServerTool(Name = "get_scale"), Description(+ "Read a Nota Scale (MIDI effect kind 2): root (C..B), scale (major minor harmonic-minor dorian phrygian lydian "+ + "mixolydian penta penta-minor chromatic custom), its degrees (semitones above the root) and note names, fold "+ + "(nearest | down | up: where an out-of-scale note goes), transpose (st, after snapping), the range (MIDI notes; "+ + "outside it notes pass through), followKey (the root follows what is played), learning (Learn mode on), card view, "+ + "and live state: the last note in / out (MIDI, -1 none), foldMap (for C..B what each pitch class plays as) and "+ + "the pitch classes held now.")]+ public Task<ScaleState> GetScale(int trackId, int index) => Read(() =>+ {+ RequireScale(trackId, index);+ float G(int p) => E.MidiEffectGetParam(trackId, index, p);+ int GI(int p) => (int)MathF.Round(G(p));+ int root = ((GI(SRoot)) % 12 + 12) % 12, mask = ScaleMask(trackId, index), fold = Math.Clamp(GI(SFold), 0, 2);+ var deg = Enumerable.Range(0, 12).Where(d => (mask >> d & 1) != 0).ToArray();+ var map = new string[12];+ for (int pc = 0; pc < 12; pc++)+ {+ int rel = ((pc - root) % 12 + 12) % 12, d = 0;+ bool Has(int x) => (mask >> ((x % 12 + 12) % 12) & 1) != 0;+ if (mask != 0 && !Has(rel))+ {+ if (fold == 1) { for (int k = 1; k < 12; k++) if (Has(rel - k)) { d = -k; break; } }+ else if (fold == 2) { for (int k = 1; k < 12; k++) if (Has(rel + k)) { d = k; break; } }+ else { for (int k = 1; k < 7; k++) { if (Has(rel + k)) { d = k; break; } if (Has(rel - k)) { d = -k; break; } } }+ }+ map[pc] = $"{PcNames[pc]}→{PcNames[((pc + d) % 12 + 12) % 12]}";+ }+ var scope = new float[32];+ int n = E.MidiEffectScope(trackId, index, scope);+ int held = n >= 6 ? (int)scope[4] : 0;+ return new ScaleState(PcNames[root], ScaleIds[Math.Clamp(GI(SScale), 0, SCustom)], deg, deg.Select(d => PcNames[(root + d) % 12]).ToArray(),+ ScaleFolds[fold], GI(STrans), GI(SLo), GI(SHi), G(SFollow) >= 0.5f, G(SLearn) >= 0.5f, G(SView) >= 0.5f ? "S" : "L",+ E.MidiEffectLastIn(trackId, index), E.MidiEffectLastOut(trackId, index), map,+ Enumerable.Range(0, 12).Where(pc => (held >> pc & 1) != 0).ToArray());+ });++ [McpServerTool(Name = "set_scale"), Description(+ "Set a Nota Scale; omit what you don't change. root C..B (or Db-style flats). scale: major minor harmonic-minor dorian "+ + "phrygian lydian mixolydian penta penta-minor chromatic custom. degrees: semitones above the root (0..11) — sets a "+ + "Custom scale (overrides scale). notes: note names (e.g. [\"D\",\"F\",\"A\"]) — a Custom scale of those pitch classes, "+ + "relative to the root. fold nearest|down|up. transpose −24..+24 st. rangeLow / rangeHigh MIDI notes 0..127 (only "+ + "notes inside are snapped). followKey: the root follows the key of what's played. learn: true starts Learn (played "+ + "notes pass through and become a fresh Custom scale), false ends it. view S|L (card size).")]+ public Task SetScale(int trackId, int index, string? root = null, string? scale = null, int[]? degrees = null, string[]? notes = null,+ string? fold = null, int? transpose = null, int? rangeLow = null, int? rangeHigh = null, bool? followKey = null, bool? learn = null,+ string? view = null) => Mutate(() =>+ {+ RequireScale(trackId, index);+ void S(int p, float v) => E.MidiEffectSetParam(trackId, index, p, v);+ if (root is not null) S(SRoot, ParsePc(root));+ if (scale is not null)+ {+ int si = Array.FindIndex(ScaleIds, x => string.Equals(x, scale.Trim().Replace(' ', '-'), StringComparison.OrdinalIgnoreCase));+ if (si < 0) throw new ArgumentException($"Unknown scale '{scale}'. Use one of: {string.Join(", ", ScaleIds)}.");+ if (si == SCustom) ScaleMakeCustom(trackId, index); else S(SScale, si);+ }+ int[]? rel = degrees;+ if (rel is null && notes is not null)+ {+ int r = ((int)MathF.Round(E.MidiEffectGetParam(trackId, index, SRoot)) % 12 + 12) % 12;+ rel = notes.Select(nm => ((ParsePc(nm) - r) % 12 + 12) % 12).ToArray();+ }+ if (rel is not null)+ {+ for (int d = 0; d < 12; d++) S(SMask + d, rel.Any(x => ((x % 12) + 12) % 12 == d) ? 1 : 0);+ S(SScale, SCustom);+ }+ if (fold is not null)+ {+ int fi = Array.FindIndex(ScaleFolds, x => string.Equals(x, fold.Trim(), StringComparison.OrdinalIgnoreCase));+ if (fi < 0) throw new ArgumentException("fold must be nearest, down or up.");+ S(SFold, fi);+ }+ if (transpose is { } t) S(STrans, Math.Clamp(t, -24, 24));+ if (rangeLow is { } lo) S(SLo, Math.Clamp(lo, 0, 127));+ if (rangeHigh is { } hi) S(SHi, Math.Clamp(hi, 0, 127));+ if (followKey is { } fk) S(SFollow, fk ? 1 : 0);+ if (learn is { } ln) S(SLearn, ln ? 1 : 0);+ if (view is not null) S(SView, view.Trim().Equals("S", StringComparison.OrdinalIgnoreCase) ? 1 : 0);+ });++ [McpServerTool(Name = "set_scale_note"), Description(+ "Add a note to or take it out of a Nota Scale (like clicking the note map): note is a name C..B (absolute pitch "+ + "class); on true adds it, false removes it. The scale in effect is copied and turns Custom.")]+ public Task SetScaleNote(int trackId, int index, string note, bool on) => Mutate(() =>+ {+ RequireScale(trackId, index);+ ScaleMakeCustom(trackId, index);+ int r = ((int)MathF.Round(E.MidiEffectGetParam(trackId, index, SRoot)) % 12 + 12) % 12;+ E.MidiEffectSetParam(trackId, index, SMask + ((ParsePc(note) - r) % 12 + 12) % 12, on ? 1 : 0);+ });++ // ---- Nota Length (kind 3) — named access in musical units --------------------------------+ // Param layout mirrors MidiNoteLength.h: Rate 0 / Gate 1 (legacy), Mode 2, Ms 3, Percent 4, Trigger 5,+ // Vel to Len 6, Key to Len 7, Random 8, Legato 9, Clip Limit 10, Division 11, View 12.+ private const int LGate = 1, LMode = 2, LMs = 3, LPct = 4, LTrig = 5, LVel = 6, LKey = 7, LRnd = 8, LLegato = 9, LClip = 10, LDiv = 11, LView = 12;+ private static readonly string[] LenModes = { "sync", "ms", "gate" };+ private static readonly string[] LenDivs = { "1/32", "1/16", "1/8", "1/4", "1/2", "1/1", "1/8.", "1/4T" };+ private static readonly double[] LenDivBeats = { 0.125, 0.25, 0.5, 1, 2, 4, 0.75, 2.0 / 3.0 };++ public sealed record LengthLastNote(int InPitch, float InVelocity, float HeldMs, int OutPitch, float OutMs);+ public sealed record LengthState(+ string Mode, string Division, float Ms, float GatePercent, float BaseLengthMs, string StartFrom,+ float VelToLenPercent, float KeyToLenPercent, float RandomPercent, bool Legato, bool ClipLimit, string View,+ LengthLastNote? LastNote, int Sounding, int Finished);++ private void RequireLength(int trackId, int index)+ {+ if (E.MidiEffectKind(trackId, index) != 3 || E.MidiEffectParamCount(trackId, index) <= LView)+ throw new ArgumentException($"MIDI effect {index} on track {trackId} is not a Nota Length.");+ }++ [McpServerTool(Name = "get_length"), Description(+ "Read a Nota Length (MIDI effect kind 3) in musical units: mode (sync | ms | gate), the sync division, the fixed ms, "+ + "the gate % (of how long each note was held), the resulting base length in ms at the current tempo (gate mode: of a "+ + "one-beat note), startFrom (note-on | note-off), the bipolar modifiers velToLenPercent / keyToLenPercent (−100..+100: "+ + "+ makes loud / low notes longer), randomPercent (± spread per note), legato, clipLimit (never cross the bar line), "+ + "card view, and live telemetry: the last note in (pitch, velocity 0..1, held ms or -1 while held) and out (pitch, "+ + "actual forced length ms), notes sounding now and notes finished so far.")]+ public Task<LengthState> GetLength(int trackId, int index) => Read(() =>+ {+ RequireLength(trackId, index);+ float G(int p) => E.MidiEffectGetParam(trackId, index, p);+ int mode = Math.Clamp((int)MathF.Round(G(LMode)), 0, 2), div = Math.Clamp((int)MathF.Round(G(LDiv)), 0, LenDivs.Length - 1);+ double msPerBeat = 60000.0 / (E.Bpm > 0 ? E.Bpm : 120);+ double baseMs = mode switch+ {+ 1 => G(LMs),+ 2 => msPerBeat * G(LPct) / 100.0,+ _ => LenDivBeats[div] * Math.Clamp(G(LGate), 0.05f, 2f) * msPerBeat,+ };+ var sc = new float[8];+ int sn = E.MidiEffectScope(trackId, index, sc);+ LengthLastNote? last = sn >= 5 && sc[0] >= 0+ ? new LengthLastNote((int)sc[0], sc[1], sc[2] < 0 ? -1 : (float)Math.Round(sc[2] * msPerBeat), (int)sc[3], (float)Math.Round(sc[4] * msPerBeat))+ : null;+ return new LengthState(LenModes[mode], LenDivs[div], G(LMs), G(LPct), (float)Math.Round(baseMs, 1), G(LTrig) >= 0.5f ? "note-off" : "note-on",+ MathF.Round(G(LVel) * 100), MathF.Round(G(LKey) * 100), MathF.Round(G(LRnd) * 100), G(LLegato) >= 0.5f, G(LClip) >= 0.5f,+ G(LView) >= 0.5f ? "S" : "L", last, sn >= 6 ? (int)sc[5] : 0, sn >= 7 ? (int)sc[6] : 0);+ });++ [McpServerTool(Name = "set_length"), Description(+ "Set a Nota Length's params by name; omit what you don't change. mode: sync | ms | gate. division: 1/32 1/16 1/8 1/4 1/2 "+ + "1/1 1/8. 1/4T (turns mode to sync unless mode is given); ms 10..2000 (turns mode to ms); gatePercent 10..200 of the "+ + "held length (turns mode to gate). startFrom: note-on | note-off (the forced note fires when the key is released). "+ + "velToLenPercent / keyToLenPercent −100..+100 (+ = loud / low notes longer, − = the opposite), randomPercent 0..100, "+ + "legato (each note lasts until the next starts), clipLimit (no note crosses the bar line it started in), view S|L.")]+ public Task SetLength(int trackId, int index, string? mode = null, string? division = null, float? ms = null, float? gatePercent = null,+ string? startFrom = null, float? velToLenPercent = null, float? keyToLenPercent = null, float? randomPercent = null,+ bool? legato = null, bool? clipLimit = null, string? view = null) => Mutate(() =>+ {+ RequireLength(trackId, index);+ void S(int p, float v) => E.MidiEffectSetParam(trackId, index, p, v);+ if (division is not null)+ {+ string d = division.Trim().Replace("D", ".", StringComparison.OrdinalIgnoreCase).Replace("t", "T");+ int di = Array.FindIndex(LenDivs, x => string.Equals(x, d, StringComparison.OrdinalIgnoreCase));+ if (di < 0) throw new ArgumentException($"Unknown division '{division}'. Use one of: {string.Join(" ", LenDivs)}.");+ S(LDiv, di); S(LGate, 1); S(LMode, 0);+ }+ if (ms is { } m) { S(LMs, Math.Clamp(m, 10, 2000)); S(LMode, 1); }+ if (gatePercent is { } g) { S(LPct, Math.Clamp(g, 10, 200)); S(LMode, 2); }+ if (mode is not null)+ {+ string mm = mode.Trim().ToLowerInvariant();+ int mi = mm.StartsWith("gate", StringComparison.Ordinal) || mm == "%" ? 2 : Array.IndexOf(LenModes, mm);+ if (mi < 0) throw new ArgumentException($"Unknown mode '{mode}'. Use one of: sync, ms, gate.");+ S(LMode, mi);+ }+ if (startFrom is not null)+ {+ string sf = startFrom.Trim().ToLowerInvariant().Replace(" ", "-").Replace("_", "-");+ if (sf is not ("note-on" or "on" or "note-off" or "off")) throw new ArgumentException("startFrom must be note-on or note-off.");+ S(LTrig, sf.EndsWith("off", StringComparison.Ordinal) ? 1 : 0);+ }+ if (velToLenPercent is { } v) S(LVel, Math.Clamp(v, -100, 100) / 100f);+ if (keyToLenPercent is { } k) S(LKey, Math.Clamp(k, -100, 100) / 100f);+ if (randomPercent is { } r) S(LRnd, Math.Clamp(r, 0, 100) / 100f);+ if (legato is { } l) S(LLegato, l ? 1 : 0);+ if (clipLimit is { } c) S(LClip, c ? 1 : 0);+ if (view is not null) S(LView, 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.+ private const int RChance = 0, RNote = 1, RVel = 2, RTime = 3, RSkip = 4, ROct = 5, RDist = 6, RRate = 7, RScale = 8,+ RLocked = 9, RSeed = 10, RView = 11, RLockBar = 12;+ private static readonly string[] RandDists = { "gauss", "even", "walk" };++ public sealed record RandomLastNote(int InPitch, float InVelocity, int OutPitch, float OutVelocity, float DelayMs, bool Skipped);+ public sealed record RandomState(+ float ChancePercent, int NoteRangeSemitones, int VelocityRange, float TimingMaxMs, float SkipPercent, int OctaveRange,+ string Distribution, string Rate, bool StayInScale, int Seed, bool Locked, int LockBar, string View,+ int Bar, int NotesIn, int Changed, int Skipped, int Queued, RandomLastNote? LastNote);++ private void RequireRandom(int trackId, int index)+ {+ if (E.MidiEffectKind(trackId, index) != 5 || E.MidiEffectParamCount(trackId, index) <= RLockBar)+ throw new ArgumentException($"MIDI effect {index} on track {trackId} is not a Nota Random.");+ }++ [McpServerTool(Name = "get_random"), Description(+ "Read a Nota Random (MIDI effect kind 5) in musical units: chancePercent (how many notes get varied), the five "+ + "amounts — noteRangeSemitones (±0..12), velocityRange (±0..64 MIDI), timingMaxMs (a 0..100 ms late shift), "+ + "skipPercent (varied notes dropped), octaveRange (±0..2) — distribution (gauss | even | walk), rate (per-note | "+ + "per-bar), stayInScale (snap into C major), seed 0..999, locked (hold one roll: lockBar's roll repeats every bar), "+ + "card view, and live telemetry: the bar being rolled, notes in / changed / skipped so far, delayed events queued, "+ + "and the last note (in pitch + velocity 0..1 → out pitch + velocity, delay ms, skipped).")]+ public Task<RandomState> GetRandom(int trackId, int index) => Read(() =>+ {+ RequireRandom(trackId, index);+ float G(int p) => E.MidiEffectGetParam(trackId, index, p);+ int R(float v) => (int)MathF.Round(v, MidpointRounding.AwayFromZero);+ var sc = new float[10];+ int sn = E.MidiEffectScope(trackId, index, sc);+ RandomLastNote? last = sn >= 9 && sc[4] >= 0+ ? new RandomLastNote((int)sc[4], sc[6], (int)sc[5], sc[7], MathF.Round(sc[8], 1), sc[5] < 0)+ : null;+ return new RandomState(MathF.Round(G(RChance) * 100), R(G(RNote)), R(G(RVel) * 64), MathF.Round(G(RTime) * 100), MathF.Round(G(RSkip) * 100),+ R(G(ROct) * 2), RandDists[Math.Clamp(R(G(RDist)), 0, 2)], G(RRate) >= 0.5f ? "per-bar" : "per-note", G(RScale) >= 0.5f,+ R(G(RSeed)), G(RLocked) >= 0.5f, R(G(RLockBar)), G(RView) >= 0.5f ? "S" : "L",+ sn >= 1 ? (int)sc[0] : 0, sn >= 2 ? (int)sc[1] : 0, sn >= 3 ? (int)sc[2] : 0, sn >= 4 ? (int)sc[3] : 0, sn >= 10 ? (int)sc[9] : 0, last);+ });++ [McpServerTool(Name = "set_random"), Description(+ "Set a Nota Random's params by name; omit what you don't change. chancePercent 0..100; noteRangeSemitones 0..12 (±); "+ + "velocityRange 0..64 (±); timingMaxMs 0..100 (notes play up to this late); skipPercent 0..100; octaveRange 0..2 (±); "+ + "distribution gauss | even | walk; rate per-note | per-bar; stayInScale (C major); seed 0..999 or reroll=true (the next "+ + "seed); locked=true holds the roll of lockBar (default: the bar the transport is in) so it repeats every bar, "+ + "locked=false rolls a new set every bar and pass; view S|L.")]+ public Task SetRandom(int trackId, int index, float? chancePercent = null, int? noteRangeSemitones = null, float? velocityRange = null,+ float? timingMaxMs = null, float? skipPercent = null, float? octaveRange = null, string? distribution = null, string? rate = null,+ bool? stayInScale = null, int? seed = null, bool? reroll = null, bool? locked = null, int? lockBar = null, string? view = null) => Mutate(() =>+ {+ RequireRandom(trackId, index);+ void S(int p, float v) => E.MidiEffectSetParam(trackId, index, p, v);+ if (chancePercent is { } c) S(RChance, Math.Clamp(c, 0, 100) / 100f);+ if (noteRangeSemitones is { } n) S(RNote, Math.Clamp(n, 0, 12));+ if (velocityRange is { } v) S(RVel, Math.Clamp(v, 0, 64) / 64f);+ if (timingMaxMs is { } t) S(RTime, Math.Clamp(t, 0, 100) / 100f);+ if (skipPercent is { } k) S(RSkip, Math.Clamp(k, 0, 100) / 100f);+ if (octaveRange is { } o) S(ROct, Math.Clamp(o, 0, 2) / 2f);+ if (distribution is not null)+ {+ int di = Array.IndexOf(RandDists, distribution.Trim().ToLowerInvariant());+ if (di < 0) throw new ArgumentException($"Unknown distribution '{distribution}'. Use one of: gauss, even, walk.");+ S(RDist, di);+ }+ if (rate is not null)+ {+ string r = rate.Trim().ToLowerInvariant().Replace(" ", "-").Replace("_", "-");+ if (r is not ("per-note" or "note" or "per-bar" or "bar")) throw new ArgumentException("rate must be per-note or per-bar.");+ S(RRate, r.EndsWith("bar", StringComparison.Ordinal) ? 1 : 0);+ }+ if (stayInScale is { } sc) S(RScale, sc ? 1 : 0);+ if (seed is { } sd) S(RSeed, Math.Clamp(sd, 0, 999));+ if (reroll == true) S(RSeed, (int)MathF.Round(E.MidiEffectGetParam(trackId, index, RSeed)) % 999 + 1);+ if (lockBar is { } lb) S(RLockBar, Math.Clamp(lb, 0, 9999));+ if (locked is { } l)+ {+ if (l && lockBar is null) S(RLockBar, Math.Max(0, (int)Math.Floor(E.PositionBeats / 4.0)));+ S(RLocked, l ? 1 : 0);+ }+ if (view is not null) S(RView, view.Trim().Equals("S", StringComparison.OrdinalIgnoreCase) ? 1 : 0);+ });}diff --git a/src/native/nota.engine/src/Engine_Render.cpp b/src/native/nota.engine/src/Engine_Render.cppindex c8eb789a..12ed239f 100644--- a/src/native/nota.engine/src/Engine_Render.cpp+++ b/src/native/nota.engine/src/Engine_Render.cpp@@ -312,7 +312,7 @@ int Engine::gatherInstrumentNotes(Track& t, MidiEv* evs, int n, int32_t frames,float vel = note.velocity;if (hasVel) vel *= std::clamp(clip.velocityEnvelope.valueAt(note.startBeat), 0.0f, 1.0f);if (clipActive && onS >= blockStart && onS < blockStart + frames && n < 1024)- evs[n++] = {static_cast<int32_t>(onS - blockStart), true, note.pitch, vel};+ evs[n++] = {static_cast<int32_t>(onS - blockStart), true, note.pitch, vel, static_cast<float>((offS - onS) / spb)};// Chase: a note already held at the jump point starts sounding right here.if (chaseNotes_ && clipActive && onS < blockStart && offS > blockStart && n < 1024)evs[n++] = {0, true, note.pitch, vel};@@ -498,7 +498,7 @@ void Engine::renderSessionSlotRaw(Track& t, float* dst, int32_t frames, double sconst double onAbs = it * L + note.startBeat;const double offAbs = onAbs + note.lengthBeats;if (onAbs >= p && onAbs < p + db && n < 1024)- evs[n++] = {static_cast<int32_t>((onAbs - p) * spb), true, note.pitch, note.velocity};+ evs[n++] = {static_cast<int32_t>((onAbs - p) * spb), true, note.pitch, note.velocity, static_cast<float>(note.lengthBeats)};if (offAbs >= p && offAbs < p + db && n < 1024)evs[n++] = {static_cast<int32_t>((offAbs - p) * spb), false, note.pitch, 0.0f};}diff --git a/src/native/nota.engine/src/MidiChord.h b/src/native/nota.engine/src/MidiChord.hindex 185ae29a..078ff80b 100644--- a/src/native/nota.engine/src/MidiChord.h+++ b/src/native/nota.engine/src/MidiChord.h@@ -121,20 +121,20 @@ public:}void process(const MidiEv* in, int nIn, MidiEv* out, int& nOut, int maxOut,- int32_t frames, double, double, bool) override {+ int32_t frames, double, double spb, bool) override {nOut = 0;const int64_t blockEnd = clock_ + frames;- auto emit = [&](int64_t at, bool on, int pitch, float vel) {+ auto emit = [&](int64_t at, bool on, int pitch, float vel, float dur = 0.0f) {if (nOut >= maxOut) return;int off = (int)(at - clock_);- out[nOut++] = { std::clamp(off, 0, std::max(0, frames - 1)), on, pitch, vel };+ out[nOut++] = { std::clamp(off, 0, std::max(0, frames - 1)), on, pitch, vel, dur };};// 1) Strummed note-ons that now fall inside this block (still flushed when bypassed,// so a chord started before the bypass completes and its offs stay balanced).for (int k = 0; k < nPend_;) {if (pend_[k].abs < blockEnd) {- emit(pend_[k].abs, true, pend_[k].pitch, pend_[k].vel);+ emit(pend_[k].abs, true, pend_[k].pitch, pend_[k].vel, pend_[k].dur);if (pend_[k].chord == chordSeq_) sounded_.fetch_add(1, std::memory_order_relaxed);pend_[k] = pend_[--nPend_];} else ++k;@@ -145,7 +145,7 @@ public:for (int i = 0; i < nIn; ++i) {const MidiEv& e = in[i];if (!e.on && keys_[e.pitch].n > 0) releaseKey(e, clock_ + e.off, emit);- else emit(clock_ + e.off, e.on, e.pitch, e.vel);+ else emit(clock_ + e.off, e.on, e.pitch, e.vel, e.dur);}clock_ = blockEnd;return;@@ -205,8 +205,10 @@ public:kk.out[kk.n++] = pit[q];if (outCount_[pit[q]]++ > 0) { sounded_.fetch_add(1, std::memory_order_relaxed); continue; } // already soundingint64_t at = absEv + (int64_t)std::llround(strumSamp * q);- if (at < blockEnd) { emit(at, true, pit[q], vel[q]); sounded_.fetch_add(1, std::memory_order_relaxed); }- else if (nPend_ < kMaxPend) pend_[nPend_++] = { at, pit[q], vel[q], chordSeq_ };+ // A clip note's length carries over (shortened by the strum delay) for devices after us.+ const float dur = e.dur > 0.0f && spb > 0.0 ? std::max(1.0f / 256.0f, e.dur - (float)(strumSamp * q / spb)) : 0.0f;+ if (at < blockEnd) { emit(at, true, pit[q], vel[q], dur); sounded_.fetch_add(1, std::memory_order_relaxed); }+ else if (nPend_ < kMaxPend) pend_[nPend_++] = { at, pit[q], vel[q], chordSeq_, dur };}++held_;}@@ -259,7 +261,7 @@ private:}static constexpr int kMaxPend = 256;- struct Pend { int64_t abs; int32_t pitch; float vel; uint32_t chord; };+ struct Pend { int64_t abs; int32_t pitch; float vel; uint32_t chord; float dur; };Pend pend_[kMaxPend];int nPend_ = 0;Key keys_[128];diff --git a/src/native/nota.engine/src/MidiDevice.h b/src/native/nota.engine/src/MidiDevice.hindex 1c7828b4..b7f066dd 100644--- a/src/native/nota.engine/src/MidiDevice.h+++ b/src/native/nota.engine/src/MidiDevice.h@@ -28,6 +28,8 @@ struct MidiEv {bool on; // true = note-on, false = note-offint32_t pitch; // 0..127float vel; // 0..1 (note-on)+ float dur = 0.0f; // note-on from a clip: its length in beats (0 = unknown, e.g. played live).+ // Lets a device that needs the length up front (Nota Length's Gate %) use it.};class MidiDevice {diff --git a/src/native/nota.engine/src/MidiNoteLength.h b/src/native/nota.engine/src/MidiNoteLength.hindex 82e3d00a..756f9791 100644--- a/src/native/nota.engine/src/MidiNoteLength.h+++ b/src/native/nota.engine/src/MidiNoteLength.h@@ -1,15 +1,20 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Nota Length — a MIDI effect (midiKind 3), reworked to mockup 3b. Forces every note to a-// chosen length: Sync (tempo division × gate), ms (absolute) or Gate % (proportion of how-// long the note was actually held). The forced note can trigger On note-on (normal) or On-// note-off (the note fires when the key is released). Length is modulated per note by-// velocity, key and randomness; Legato retriggers held notes and Clip Limit stops a forced-// note from outlasting the played note. Off scheduling uses a pending queue in absolute-// beats (tempo-safe), like the arpeggiator.+// Nota Length — a MIDI effect (midiKind 3), almanac rework (mockups 1a / 1b). Forces every+// note to a chosen length: Sync (a tempo division), ms (absolute) or Gate % (a proportion of+// how long the note was actually held). The forced note starts from the note-on (normal) or+// from the note-off (it fires when the key is released, the length added after the played+// note). Length is shaped per note by velocity and key (bipolar: + makes loud / low notes+// longer, − the opposite) and by Random (± spread per note). Legato stretches each note to+// the start of the next one; Clip length limit stops a forced note from crossing the bar+// line it started in (4/4). Off scheduling uses a pending queue in absolute beats+// (tempo-safe), like the arpeggiator. Gate % reads a clip note's length from the note-on+// (MidiEv::dur), so it can also shorten; a note played live is measured at its note-off.//-// Param layout is APPEND-ONLY: 0 Rate / 1 Gate stay put so old projects load unchanged.+// Param layout is APPEND-ONLY. 0 Rate / 1 Gate are the pre-almanac sync controls (4 rates ×+// gate): Division (11) replaced Rate — the managed loader maps an old Rate onto it — and+// Gate stays as a hidden multiplier (1 = off) so old projects keep their sound.#pragma once@@ -27,12 +32,18 @@ public:enum Param {PRate = 0, PGate, PMode, PMs, PPercent, PTrigger,PVelToLen, PKeyToLen, PRandom, PLegato, PClipLimit,+ PDivision, PView,kNumParams};- // Sync divisions (beats): 1/16, 1/8, 1/8 dotted, 1/4.- static constexpr double kDiv[4] = { 0.25, 0.5, 0.75, 1.0 };+ // Sync divisions (beats): 1/32, 1/16, 1/8, 1/4, 1/2, 1/1, 1/8 dotted, 1/4 triplet.+ static constexpr int kNumDiv = 8;+ static constexpr double kDiv[kNumDiv] = { 0.125, 0.25, 0.5, 1.0, 2.0, 4.0, 0.75, 2.0 / 3.0 };+ static constexpr double kBar = 4.0; // beats per bar for Legato / Clip (4/4)- MidiNoteLength() { p_[PRate].store(1.0f); p_[PGate].store(1.0f); p_[PMs].store(250.0f); p_[PPercent].store(100.0f); }+ MidiNoteLength() {+ p_[PRate].store(1.0f); p_[PGate].store(1.0f); p_[PMs].store(250.0f); p_[PPercent].store(100.0f);+ p_[PDivision].store(2.0f); // 1/8 — what the old default (Rate 1/8 × Gate 1) played+ }int32_t midiKind() const override { return 3; }const char* displayName() const override { return "Nota Length"; }@@ -44,20 +55,43 @@ public:switch (i) {case PRate: return "Rate"; case PGate: return "Gate"; case PMode: return "Mode"; case PMs: return "Ms";case PPercent: return "Percent"; case PTrigger: return "Trigger"; case PVelToLen: return "Vel to Len";- case PKeyToLen: return "Key to Len"; case PRandom: return "Random"; case PLegato: return "Legato"; case PClipLimit: return "Clip Limit";+ case PKeyToLen: return "Key to Len"; case PRandom: return "Random"; case PLegato: return "Legato";+ case PClipLimit: return "Clip Limit"; case PDivision: return "Division"; case PView: return "View";default: return "";}}- float paramMin(int32_t) const override { return 0.0f; }+ float paramMin(int32_t i) const override {+ switch (i) {+ case PMs: case PPercent: return 10.0f;+ case PVelToLen: case PKeyToLen: return -1.0f;+ default: return 0.0f;+ }+ }float paramMax(int32_t i) const override {switch (i) {case PRate: return 3.0f; case PGate: return 2.0f; case PMode: return 2.0f; case PMs: return 2000.0f;- case PPercent: return 200.0f; default: return 1.0f; // trigger / modifiers / legato / cliplimit+ case PPercent: return 200.0f; case PDivision: return (float)(kNumDiv - 1);+ default: return 1.0f; // trigger / modifiers / legato / clip / view}}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); }- void reset() override { nPending_ = 0; nHeld_ = 0; intBeat_ = 0.0; }+ void reset() override { nPending_ = 0; nHeld_ = 0; nSound_ = 0; intBeat_ = 0.0; sounding_.store(0, std::memory_order_relaxed); }++ // Editor / MCP telemetry: [0] last input pitch, [1] its velocity 0..1, [2] its held length+ // (beats, −1 = still held), [3] last finished output pitch, [4] its actual length (beats),+ // [5] notes sounding now, [6] notes finished since the device was created.+ int32_t midiScope(float* out, int32_t maxN) const override {+ const float v[7] = { (float)lastInPitch_.load(std::memory_order_relaxed), lastInVel_.load(std::memory_order_relaxed),+ lastInHeld_.load(std::memory_order_relaxed), (float)lastOutPitch_.load(std::memory_order_relaxed),+ lastOutLen_.load(std::memory_order_relaxed), (float)sounding_.load(std::memory_order_relaxed),+ (float)finished_.load(std::memory_order_relaxed) };+ const int n = std::min<int32_t>(maxN, 7);+ for (int i = 0; i < n; ++i) out[i] = v[i];+ return n;+ }+ int32_t midiLastIn() const override { return lastInPitch_.load(std::memory_order_relaxed); }+ int32_t midiLastOut() const override { return lastOutPitch_.load(std::memory_order_relaxed); }std::shared_ptr<MidiDevice> clone() const override {auto c = std::make_shared<MidiNoteLength>();@@ -69,99 +103,136 @@ public:void process(const MidiEv* in, int nIn, MidiEv* out, int& nOut, int maxOut,int32_t frames, double beatStart, double spb, bool playing) override {nOut = 0;- if (bypassed()) { for (int i = 0; i < nIn && nOut < maxOut; ++i) out[nOut++] = in[i]; intBeat_ = playing ? beatStart : intBeat_; return; }const double b0 = playing ? beatStart : intBeat_;const double b1 = b0 + frames / spb;+ if (bypassed()) {+ // Release what we still hold, then pass through untouched.+ for (int i = 0; i < nPending_ && nOut < maxOut; ++i) out[nOut++] = { 0, false, pending_[i].pitch, 0.0f };+ nPending_ = 0; nHeld_ = 0; nSound_ = 0; sounding_.store(0, std::memory_order_relaxed);+ for (int i = 0; i < nIn && nOut < maxOut; ++i) out[nOut++] = in[i];+ intBeat_ = b1;+ return;+ }const int mode = std::clamp((int)std::lround(p_[PMode].load(std::memory_order_relaxed)), 0, 2);- const bool onOff = p_[PTrigger].load(std::memory_order_relaxed) >= 0.5f; // fire on note-off+ const bool onOff = p_[PTrigger].load(std::memory_order_relaxed) >= 0.5f; // start from the note-offconst bool legato = p_[PLegato].load(std::memory_order_relaxed) >= 0.5f;const bool clip = p_[PClipLimit].load(std::memory_order_relaxed) >= 0.5f;- // Emit due offs from earlier blocks.- for (int i = 0; i < nPending_;) {- if (pending_[i].beat < b1) {- int32_t o = off(std::max(0.0, pending_[i].beat - b0), spb, frames);- if (nOut < maxOut) out[nOut++] = { o, false, pending_[i].pitch, 0.0f };- pending_[i] = pending_[--nPending_];- } else ++i;- }+ // Offs falling due before `until` go out at their own time (never before the block).+ auto flushDue = [&](double until) {+ for (int k = 0; k < nPending_;) {+ const double off = pending_[k].off;+ if (off < until) emitOff(k, std::max(b0, off), b0, spb, frames, out, nOut, maxOut);+ else ++k;+ }+ };for (int i = 0; i < nIn; ++i) {const MidiEv& e = in[i];const double evBeat = b0 + (double)e.off / spb;+ flushDue(evBeat);if (e.on) {addHeld(e.pitch, evBeat, e.vel);- if (!onOff) {- if (legato) cutAll(e.off, out, nOut, maxOut);- if (nOut < maxOut) out[nOut++] = e; // pass the on through- if (mode != 2) fireOff(e.pitch, evBeat, len(e.vel, e.pitch, 0.0, mode, spb), b0, b1, spb, frames, out, nOut, maxOut);- // Gate% waits for the note-off to know the held length.- }+ lastInPitch_.store(e.pitch, std::memory_order_relaxed); lastInVel_.store(e.vel, std::memory_order_relaxed);+ lastInHeld_.store(-1.0f, std::memory_order_relaxed);+ if (onOff) continue; // fires on release+ start(e.pitch, e.vel, evBeat, b0, spb, frames, legato, out, nOut, maxOut);+ if (legato || mode != 2) schedule(e.pitch, evBeat, legato ? -1.0 : len(e.vel, e.pitch, 0.0, mode, spb), clip, legato);+ else if (e.dur > 0.0f) schedule(e.pitch, evBeat, len(e.vel, e.pitch, e.dur, 2, spb), clip, false); // a clip note: length known+ // else Gate % waits for the note-off to know the held length (played live).} else {Held* h = findHeld(e.pitch);const float hv = h ? h->vel : 0.8f;- const double heldBeats = h ? std::max(0.0, evBeat - h->onBeat) : 0.25;const double onBeat = h ? h->onBeat : evBeat;+ const double heldBeats = std::max(0.0, evBeat - onBeat);+ if (h) lastInHeld_.store((float)heldBeats, std::memory_order_relaxed);+ removeHeld(e.pitch);if (onOff) {- if (legato) cutAll(e.off, out, nOut, maxOut);- if (nOut < maxOut) out[nOut++] = { e.off, true, e.pitch, hv }; // fire the note on release- fireOff(e.pitch, evBeat, len(hv, e.pitch, heldBeats, mode, spb), b0, b1, spb, frames, out, nOut, maxOut);- } else if (mode == 2) {- fireOff(e.pitch, onBeat, len(hv, e.pitch, heldBeats, 2, spb), b0, b1, spb, frames, out, nOut, maxOut);- } else if (clip) {- if (cancelPending(e.pitch) && nOut < maxOut) out[nOut++] = { e.off, false, e.pitch, 0.0f }; // don't outlast the played note+ start(e.pitch, hv, evBeat, b0, spb, frames, legato, out, nOut, maxOut);+ schedule(e.pitch, evBeat, legato ? -1.0 : len(hv, e.pitch, heldBeats, mode, spb), clip, legato);+ } else if (mode == 2 && !legato && findPending(e.pitch) < 0 && h && sounding(e.pitch)) {+ schedule(e.pitch, onBeat, len(hv, e.pitch, heldBeats, 2, spb), clip, false);}- // else: swallow the incoming off (fixed forced length wins)- removeHeld(e.pitch);+ // else: swallow the incoming off (the forced length wins)+ }+ // An off already overdue (Gate % below 100 % learns the length at the note-off) goes out now.+ for (int k = 0; k < nPending_;) {+ if (pending_[k].off <= evBeat) emitOff(k, evBeat, b0, spb, frames, out, nOut, maxOut);+ else ++k;}}+ flushDue(b1);intBeat_ = b1;}private:- // Length in beats for one note, with the velocity / key / random modifiers.+ // Length in beats for one note, with the velocity / key / random modifiers (mirrors the card's model).double len(float vel, int pitch, double heldBeats, int mode, double spb) {double L;if (mode == 2) L = heldBeats * (std::clamp(p_[PPercent].load(std::memory_order_relaxed), 1.0f, 200.0f) / 100.0);- else if (mode == 1) L = (std::max(1.0f, p_[PMs].load(std::memory_order_relaxed)) / 1000.0) * sr_ / spb; // ms → beats- else L = kDiv[std::clamp((int)std::lround(p_[PRate].load(std::memory_order_relaxed)), 0, 3)]+ else if (mode == 1) L = (std::clamp(p_[PMs].load(std::memory_order_relaxed), 1.0f, 2000.0f) / 1000.0) * sr_ / spb; // ms → beats+ else L = kDiv[std::clamp((int)std::lround(p_[PDivision].load(std::memory_order_relaxed)), 0, kNumDiv - 1)]* std::clamp(p_[PGate].load(std::memory_order_relaxed), 0.05f, 2.0f);- L *= 1.0 + (double)p_[PVelToLen].load(std::memory_order_relaxed) * ((double)vel - 0.5) * 2.0;- L *= 1.0 + (double)p_[PKeyToLen].load(std::memory_order_relaxed) * ((pitch - 60) / 36.0);- const float rnd = p_[PRandom].load(std::memory_order_relaxed);- if (rnd > 0.0f) L *= 1.0 + (double)rnd * ((double)frand() - 0.5) * 2.0;- return std::max(0.01, L);+ const double velAmt = std::clamp(p_[PVelToLen].load(std::memory_order_relaxed), -1.0f, 1.0f);+ const double keyAmt = std::clamp(p_[PKeyToLen].load(std::memory_order_relaxed), -1.0f, 1.0f);+ L *= std::max(0.05, 1.0 + velAmt * ((double)vel * 127.0 - 64.0) / 64.0); // + : loud notes longer+ L *= std::max(0.05, 1.0 - keyAmt * (pitch - 60) / 24.0); // + : low notes longer+ const float rnd = std::clamp(p_[PRandom].load(std::memory_order_relaxed), 0.0f, 1.0f);+ if (rnd > 0.0f) L *= 1.0 + (double)rnd * ((double)frand() * 2.0 - 1.0);+ return std::max(1.0 / 256.0, L);}- void fireOff(int pitch, double onBeat, double lenBeats, double b0, double b1, double spb, int frames,- MidiEv* out, int& nOut, int maxOut) {- const double offBeat = onBeat + lenBeats;- if (offBeat < b1) { if (nOut < maxOut) out[nOut++] = { off(std::max(0.0, offBeat - b0), spb, frames), false, pitch, 0.0f }; }- else if (nPending_ < kMaxPending) pending_[nPending_++] = { pitch, offBeat };+ static double barEnd(double beat) { return (std::floor(beat / kBar + 1e-9) + 1.0) * kBar; }++ // A forced note starts: legato cuts whatever still sounds, a same-pitch note is retriggered.+ void start(int32_t pitch, float vel, double beat, double b0, double spb, int32_t frames, bool legato,+ MidiEv* out, int& nOut, int maxOut) {+ for (int k = 0; k < nPending_;) {+ if (legato || pending_[k].pitch == pitch) emitOff(k, beat, b0, spb, frames, out, nOut, maxOut);+ else ++k;+ }+ if (nOut < maxOut) out[nOut++] = { at(beat, b0, spb, frames), true, pitch, vel };+ sounding_.fetch_add(1, std::memory_order_relaxed);+ if (nSound_ < kMaxPending) sound_[nSound_++] = { pitch, beat };}- void cutAll(int32_t offInBlock, MidiEv* out, int& nOut, int maxOut) {- for (int i = 0; i < nPending_; ++i) if (nOut < maxOut) out[nOut++] = { offInBlock, false, pending_[i].pitch, 0.0f };- nPending_ = 0;+ // Queue the off: lenBeats < 0 = legato (held until the next note starts, at most to the bar line).+ void schedule(int32_t pitch, double onBeat, double lenBeats, bool clip, bool legato) {+ double off = legato || lenBeats < 0 ? barEnd(onBeat) : onBeat + lenBeats;+ if (clip) off = std::min(off, barEnd(onBeat));+ if (nPending_ < kMaxPending) pending_[nPending_++] = { pitch, onBeat, std::max(off, onBeat + 1.0 / 256.0) };}- bool cancelPending(int32_t pitch) {- for (int i = 0; i < nPending_; ++i) if (pending_[i].pitch == pitch) { pending_[i] = pending_[--nPending_]; return true; }- return false;+ void emitOff(int k, double beat, double b0, double spb, int32_t frames, MidiEv* out, int& nOut, int maxOut) {+ const Off p = pending_[k];+ pending_[k] = pending_[--nPending_];+ if (nOut < maxOut) out[nOut++] = { at(beat, b0, spb, frames), false, p.pitch, 0.0f };+ lastOutPitch_.store(p.pitch, std::memory_order_relaxed);+ lastOutLen_.store((float)std::max(0.0, beat - p.on), std::memory_order_relaxed);+ finished_.fetch_add(1, std::memory_order_relaxed);+ for (int s = 0; s < nSound_; ++s) if (sound_[s].pitch == p.pitch) { sound_[s] = sound_[--nSound_]; break; }+ sounding_.store(nSound_, std::memory_order_relaxed);}+ bool sounding(int32_t pitch) const { for (int s = 0; s < nSound_; ++s) if (sound_[s].pitch == pitch) return true; return false; }+ int findPending(int32_t pitch) const { for (int i = 0; i < nPending_; ++i) if (pending_[i].pitch == pitch) return i; return -1; }+struct Held { int32_t pitch; double onBeat; float vel; };Held* findHeld(int32_t pitch) { for (int i = 0; i < nHeld_; ++i) if (held_[i].pitch == pitch) return &held_[i]; return nullptr; }void addHeld(int32_t pitch, double onBeat, float vel) { if (auto* h = findHeld(pitch)) { h->onBeat = onBeat; h->vel = vel; return; } if (nHeld_ < kMaxHeld) held_[nHeld_++] = { pitch, onBeat, vel }; }void removeHeld(int32_t pitch) { for (int i = 0; i < nHeld_; ++i) if (held_[i].pitch == pitch) { held_[i] = held_[--nHeld_]; return; } }- static int32_t off(double beats, double spb, int32_t frames) {- long v = (long)std::floor(beats * spb + 0.5); if (v < 0) v = 0; if (v >= frames) v = frames - 1; return (int32_t)v;+ static int32_t at(double beat, double b0, double spb, int32_t frames) {+ long v = (long)std::floor((beat - b0) * spb + 0.5); if (v < 0) v = 0; if (v >= frames) v = frames - 1; return (int32_t)v;}float frand() { rng_ ^= rng_ << 13; rng_ ^= rng_ >> 17; rng_ ^= rng_ << 5; return (rng_ & 0xFFFFFF) / (float)0x1000000; }- struct Off { int32_t pitch; double beat; };+ struct Off { int32_t pitch; double on, off; };+ struct Sound { int32_t pitch; double on; };static constexpr int kMaxPending = 128, kMaxHeld = 64;- Off pending_[kMaxPending]; int nPending_ = 0;- Held held_[kMaxHeld]; int nHeld_ = 0;+ Off pending_[kMaxPending]; int nPending_ = 0;+ Sound sound_[kMaxPending]; int nSound_ = 0; // forced notes started and not yet released+ Held held_[kMaxHeld]; int nHeld_ = 0;double intBeat_ = 0.0, sr_ = 44100.0;uint32_t rng_ = 0x9E3779B9u;std::atomic<float> p_[kNumParams];+ std::atomic<int32_t> lastInPitch_{-1}, lastOutPitch_{-1}, sounding_{0}, finished_{0};+ std::atomic<float> lastInVel_{0.0f}, lastInHeld_{-1.0f}, lastOutLen_{0.0f};};} // namespace notadiff --git a/src/native/nota.engine/src/MidiRandom.h b/src/native/nota.engine/src/MidiRandom.hindex 6abd7763..1115e832 100644--- a/src/native/nota.engine/src/MidiRandom.h+++ b/src/native/nota.engine/src/MidiRandom.h@@ -1,12 +1,19 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Nota Random — a MIDI effect (midiKind 5), reworked to mockup 3b. With probability Chance,-// a note is humanised across up to five dimensions: Note (±semitones), Velocity, Timing-// (micro-shift), Skip (drop it) and Octave — each with its own amount. The random values are-// shaped by a Distribution (Gauss / Even / Walk), drawn Per note or Per bar, optionally kept-// in scale, and reproducible when the Seed is Locked. A note-on and its note-off transpose-// identically (offset remembered per pitch), and skipped notes drop both events.+// Nota Random — a MIDI effect (midiKind 5), almanac rework (mockups 1a / 1b). With probability+// Chance a note is varied across up to five dimensions: Note (±semitones), Velocity (±64),+// Timing (a 0..100 ms delay — a real-time effect can only play late), Skip (drop it) and+// Octave (±2). The random values are shaped by a Distribution — Gauss (a bell), Even (flat)+// or Walk (a bounded random walk that drifts from note to note) — drawn Per note or once Per+// bar, and optionally snapped into C major (Stay in scale).+//+// The roll is keyed on the Seed and the bar: every bar is a fresh roll, and each note's draw+// is a pure function of (seed, bar, its position in the bar, pitch) — so the editor can show+// exactly what will play. Unlocked, a new pass (after a stop or a loop wrap) re-rolls too;+// Locked holds one roll (the bar that was showing when Lock was pressed — "Lock Bar") and+// repeats it every bar, reproducibly. A note-on and its note-off move identically (transpose+// and delay remembered per pitch), and a skipped note drops both events.//// Param layout is APPEND-ONLY: 0 Chance / 1 Note Range stay put so old projects load unchanged.@@ -27,12 +34,18 @@ public:enum Param {PChance = 0, PNoteRange, PVelAmt, PTimeAmt, PSkip, POctAmt,PDist, PRate, PStayInScale, PLocked, PSeed,+ PView, // editor card size (0 = L, 1 = S) — not a sound param+ PLockBar, // the bar whose roll Lock holdskNumParams};+ static constexpr double kBarBeats = 4.0;+ static constexpr double kMaxDelayMs = 100.0;+MidiRandom() {p_[PChance].store(0.5f); p_[PNoteRange].store(7.0f);p_[PVelAmt].store(0.0f); p_[PTimeAmt].store(0.0f); p_[PSkip].store(0.0f); p_[POctAmt].store(0.0f);p_[PDist].store(0.0f); p_[PRate].store(0.0f); p_[PStayInScale].store(0.0f); p_[PLocked].store(0.0f); p_[PSeed].store(1.0f);+ p_[PView].store(0.0f); p_[PLockBar].store(0.0f);}int32_t midiKind() const override { return 5; }@@ -46,32 +59,81 @@ public:case PChance: return "Chance"; case PNoteRange: return "Note Range"; case PVelAmt: return "Vel Amt";case PTimeAmt: return "Time Amt"; case PSkip: return "Skip"; case POctAmt: return "Oct Amt";case PDist: return "Dist"; case PRate: return "Rate"; case PStayInScale: return "Stay In Scale";- case PLocked: return "Locked"; case PSeed: return "Seed"; default: return "";+ case PLocked: return "Locked"; case PSeed: return "Seed"; case PView: return "View"; case PLockBar: return "Lock Bar";+ default: return "";}}float paramMin(int32_t) const override { return 0.0f; }float paramMax(int32_t i) const override {- switch (i) { case PNoteRange: return 12.0f; case PDist: return 2.0f; case PSeed: return 999.0f; default: return 1.0f; }+ switch (i) {+ case PNoteRange: return 12.0f; case PDist: return 2.0f; case PSeed: return 999.0f; case PLockBar: return 9999.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); }void reset() override {- std::memset(offset_, 0, sizeof(offset_)); std::memset(skipped_, 0, sizeof(skipped_));- walk_ = 0.0f; noteCounter_ = 0; lastBar_ = INT64_MIN; intBeat_ = 0.0;+ std::memset(offset_, 0, sizeof(offset_)); std::memset(skipped_, 0, sizeof(skipped_)); std::memset(delay_, 0, sizeof(delay_));+ nQueue_ = 0; lastRollKey_ = UINT64_MAX; intBeat_ = 0.0;+ pass_.fetch_add(1, std::memory_order_relaxed);+ }++ // Editor / MCP telemetry: [0] the bar being rolled, [1] notes in, [2] notes changed,+ // [3] notes skipped (counts since the device was created), [4] last input pitch, [5] its+ // output pitch (−1 = skipped), [6] input velocity 0..1, [7] output velocity, [8] its delay+ // in ms, [9] events waiting in the delay queue.+ int32_t midiScope(float* out, int32_t maxN) const override {+ const float v[10] = {+ (float)bar_.load(std::memory_order_relaxed), (float)notesIn_.load(std::memory_order_relaxed),+ (float)changed_.load(std::memory_order_relaxed), (float)skippedN_.load(std::memory_order_relaxed),+ (float)lastIn_.load(std::memory_order_relaxed), (float)lastOut_.load(std::memory_order_relaxed),+ lastInVel_.load(std::memory_order_relaxed), lastOutVel_.load(std::memory_order_relaxed),+ lastDelayMs_.load(std::memory_order_relaxed), (float)queued_.load(std::memory_order_relaxed) };+ const int n = std::min<int32_t>(maxN, 10);+ for (int i = 0; i < n; ++i) out[i] = v[i];+ return n;}+ int32_t midiLastIn() const override { return lastIn_.load(std::memory_order_relaxed); }+ int32_t midiLastOut() const override { return lastOut_.load(std::memory_order_relaxed); }std::shared_ptr<MidiDevice> clone() const override {auto c = std::make_shared<MidiRandom>();for (int i = 0; i < kNumParams; ++i) c->p_[i].store(p_[i].load(std::memory_order_relaxed));+ c->sr_ = sr_;c->setBypassed(bypassed());return c;}+ // ---- the roll (shared with the editor's model, which ports these exactly) -------------------+ static uint32_t hash(uint32_t a, uint32_t b) { uint32_t h = a * 2654435761u + b * 40503u + 0x9e3779b9u; h ^= h >> 15; h *= 0x2c1b3c6du; h ^= h >> 12; return h; }+ static float u01(uint32_t& s) { s = s * 1664525u + 1013904223u; return (float)(s >> 8) / 16777216.0f; }+ // One draw in −1..1 from the distribution. Walk steps the caller's walk state (reflecting+ // at ±1); Gauss is a Box–Muller normal scaled so ±1 ≈ 2.6 σ.+ static float draw(int dist, uint32_t& s, float& walk) {+ if (dist == 1) return u01(s) * 2.0f - 1.0f;+ if (dist == 2) {+ walk += (u01(s) * 2.0f - 1.0f) * 0.45f;+ if (walk > 1.0f) walk = 2.0f - walk;+ if (walk < -1.0f) walk = -2.0f - walk;+ return walk;+ }+ const float a = std::max(u01(s), 1e-9f), b = u01(s);+ const float g = std::sqrt(-2.0f * std::log(a)) * std::cos(6.2831853f * b);+ return std::clamp(g / 2.6f, -1.0f, 1.0f);+ }+ static int snapToCMajor(int p) {+ static const bool in[12] = { true, false, true, false, true, true, false, true, false, true, false, true };+ return in[((p % 12) + 12) % 12] ? p : p - 1;+ }+ static uint32_t rollKey(uint32_t seed, uint32_t barKey) { return hash(seed * 7919u + 17u, barKey * 104729u + 3u); }+ static uint32_t noteKey(uint32_t roll, int tick, int pitch) { return hash(roll, (uint32_t)tick * 128u + (uint32_t)pitch); }+void process(const MidiEv* in, int nIn, MidiEv* out, int& nOut, int maxOut,int32_t frames, double beatStart, double spb, bool playing) override {nOut = 0;- if (bypassed()) { for (int i = 0; i < nIn && nOut < maxOut; ++i) out[nOut++] = in[i]; intBeat_ = playing ? beatStart : intBeat_; return; }const double b0 = playing ? beatStart : intBeat_;+ const int64_t blockStart = clock_;+ const bool by = bypassed();const float chance = std::clamp(p_[PChance].load(std::memory_order_relaxed), 0.0f, 1.0f);const int nr = std::clamp((int)std::lround(p_[PNoteRange].load(std::memory_order_relaxed)), 0, 12);const float velAmt = std::clamp(p_[PVelAmt].load(std::memory_order_relaxed), 0.0f, 1.0f);@@ -82,89 +144,112 @@ public:const bool perBar = p_[PRate].load(std::memory_order_relaxed) >= 0.5f;const bool stay = p_[PStayInScale].load(std::memory_order_relaxed) >= 0.5f;const bool locked = p_[PLocked].load(std::memory_order_relaxed) >= 0.5f;- const uint32_t seed = (uint32_t)std::lround(p_[PSeed].load(std::memory_order_relaxed));+ const uint32_t seed = (uint32_t)std::lround(std::max(0.0f, p_[PSeed].load(std::memory_order_relaxed)));+ const uint32_t lockBar = (uint32_t)std::lround(std::max(0.0f, p_[PLockBar].load(std::memory_order_relaxed)));+ const uint32_t pass = locked ? 0u : pass_.load(std::memory_order_relaxed);for (int i = 0; i < nIn; ++i) {const MidiEv& e = in[i];- if (e.pitch < 0 || e.pitch > 127) { if (nOut < maxOut) out[nOut++] = e; continue; }- if (e.on) {- const double noteBeat = b0 + (double)e.off / spb;- // Locked → key the randomness on the note's musical position + pitch so it is- // reproducible across playbacks with no running state; unlocked → free RNG.- const uint32_t beatKey = hash(hash(seed, (uint32_t)std::llround(std::max(0.0, noteBeat) * 480.0)), (uint32_t)e.pitch);- uint32_t ns = locked ? hash(beatKey, 0xA5A5A5A5u) : rng_;- bool active = next(ns) < chance;- bool skip = active && skipAmt > 0.0f && next(ns) < skipAmt;- if (!locked) rng_ = ns;-- int pitchOff = 0, oct = 0, timeSamp = 0; float velOff = 0.0f;- if (active) {- if (perBar) {- int64_t bar = (int64_t)std::floor(noteBeat / 4.0);- if (bar != lastBar_) { lastBar_ = bar; drawSet(locked ? hash(seed ^ 0x5bd1e995u, (uint32_t)bar) : rng_, dist, nr, octAmt, velAmt, timeAmt, locked); }- pitchOff = barPitch_; oct = barOct_; velOff = barVel_; timeSamp = barTime_;- } else {- uint32_t os = locked ? hash(beatKey, 0x3c6ef35fu) : rng_;- pitchOff = pickPitch(dist, os, nr, !locked); oct = pickOct(os, octAmt); velOff = pickVel(os, velAmt); timeSamp = pickTime(os, timeAmt);- if (!locked) rng_ = os;- }- }- ++noteCounter_;-- if (skip) { skipped_[e.pitch] = 1; continue; }- skipped_[e.pitch] = 0;- int delta = stay ? foldToMajor(pitchOff + oct) : pitchOff + oct;- int outPitch = std::clamp(e.pitch + delta, 0, 127);- offset_[e.pitch] = (int8_t)std::clamp(outPitch - e.pitch, -120, 120);- float outVel = std::clamp(e.vel + velOff, 0.0f, 1.0f);- int outOff = std::clamp((int)e.off + timeSamp, 0, frames - 1);- if (nOut < maxOut) out[nOut++] = { outOff, true, outPitch, outVel };- } else {- if (skipped_[e.pitch]) { skipped_[e.pitch] = 0; continue; } // drop the off for a skipped note- int p = std::clamp(e.pitch + offset_[e.pitch], 0, 127);- if (nOut < maxOut) out[nOut++] = { e.off, false, p, e.vel };+ if (e.pitch < 0 || e.pitch > 127) { push(out, nOut, maxOut, e); continue; }+ if (!e.on) {+ const int p = e.pitch;+ if (skipped_[p]) { skipped_[p] = 0; continue; } // the off of a skipped note+ MidiEv off{ e.off, false, std::clamp(p + offset_[p], 0, 127), e.vel };+ if (delay_[p] > 0) enqueue(blockStart + e.off + delay_[p], off); else push(out, nOut, maxOut, off);+ offset_[p] = 0; delay_[p] = 0;+ continue;}+ if (by) { offset_[e.pitch] = 0; delay_[e.pitch] = 0; skipped_[e.pitch] = 0; push(out, nOut, maxOut, e); continue; }++ const double noteBeat = std::max(0.0, b0 + (double)e.off / spb);+ const int64_t bar = (int64_t)std::floor(noteBeat / kBarBeats + 1e-9);+ const uint32_t barKey = locked ? lockBar : (uint32_t)bar;+ const uint32_t roll = rollKey(seed, barKey) ^ (pass * 0x85ebca6bu);+ const uint64_t rk = ((uint64_t)barKey << 32) ^ (uint64_t)(uint32_t)bar ^ ((uint64_t)pass << 20);+ if (rk != lastRollKey_) { // a new bar: walks restart, the per-bar set re-draws+ lastRollKey_ = rk;+ walk_[0] = walk_[1] = walk_[2] = walk_[3] = 0.0f;+ uint32_t bs = hash(roll, 0xB0B5EEDu); float w[4] = { 0, 0, 0, 0 };+ for (int d = 0; d < 4; ++d) barD_[d] = draw(dist, bs, w[d]);+ }+ const int tick = (int)std::lround((noteBeat - (double)bar * kBarBeats) * 480.0);+ const uint32_t nk = noteKey(roll, tick, e.pitch);+ uint32_t hs = hash(nk, 0xA5A5A5A5u);+ const bool hit = u01(hs) < chance;+ const bool skip = hit && u01(hs) < skipAmt;+ float D[4] = { 0, 0, 0, 0 };+ if (perBar) { for (int d = 0; d < 4; ++d) D[d] = barD_[d]; }+ else { uint32_t ds = hash(nk, 0x3c6ef35fu); for (int d = 0; d < 4; ++d) D[d] = draw(dist, ds, walk_[d]); }++ int outPitch = e.pitch; float outVel = e.vel; int32_t delay = 0;+ if (hit) {+ outPitch = e.pitch + (int)std::lround(D[0] * nr) + 12 * (int)std::lround(D[3] * octAmt * 2.0f);+ if (stay) outPitch = snapToCMajor(outPitch);+ outPitch = std::clamp(outPitch, 0, 127);+ outVel = std::clamp(e.vel + D[1] * velAmt * 64.0f / 127.0f, 1.0f / 127.0f, 1.0f);+ delay = (int32_t)std::lround(std::fabs(D[2]) * timeAmt * kMaxDelayMs * 0.001 * sr_);+ }+ bar_.store((int32_t)bar, std::memory_order_relaxed);+ notesIn_.fetch_add(1, std::memory_order_relaxed);+ lastIn_.store(e.pitch, std::memory_order_relaxed); lastInVel_.store(e.vel, std::memory_order_relaxed);+ if (skip) {+ skipped_[e.pitch] = 1; offset_[e.pitch] = 0; delay_[e.pitch] = 0;+ skippedN_.fetch_add(1, std::memory_order_relaxed);+ lastOut_.store(-1, std::memory_order_relaxed); lastOutVel_.store(0.0f, std::memory_order_relaxed); lastDelayMs_.store(0.0f, std::memory_order_relaxed);+ continue;+ }+ if (outPitch != e.pitch || std::fabs(outVel - e.vel) > 0.5f / 127.0f || delay > 0) changed_.fetch_add(1, std::memory_order_relaxed);+ lastOut_.store(outPitch, std::memory_order_relaxed); lastOutVel_.store(outVel, std::memory_order_relaxed);+ lastDelayMs_.store((float)(delay * 1000.0 / sr_), std::memory_order_relaxed);+ skipped_[e.pitch] = 0;+ offset_[e.pitch] = (int8_t)std::clamp(outPitch - e.pitch, -120, 120);+ delay_[e.pitch] = delay;+ MidiEv on{ e.off, true, outPitch, outVel, e.dur };+ if (delay > 0) enqueue(blockStart + e.off + delay, on); else push(out, nOut, maxOut, on);+ }++ // Delayed events falling due in this block.+ for (int k = 0; k < nQueue_;) {+ if (queue_[k].due < blockStart + frames) {+ MidiEv ev = queue_[k].ev;+ ev.off = (int32_t)std::clamp<int64_t>(queue_[k].due - blockStart, 0, frames - 1);+ push(out, nOut, maxOut, ev);+ queue_[k] = queue_[--nQueue_];+ } else ++k;}+ queued_.store(nQueue_, std::memory_order_relaxed);+ // Keep the block sorted by offset (stable; offs before ons at the same sample).+ for (int a = 1; a < nOut; ++a) {+ MidiEv v = out[a]; int b = a - 1;+ while (b >= 0 && (out[b].off > v.off || (out[b].off == v.off && out[b].on && !v.on))) { out[b + 1] = out[b]; --b; }+ out[b + 1] = v;+ }+ clock_ += frames;intBeat_ = b0 + frames / spb;}private:- static uint32_t hash(uint32_t a, uint32_t b) { uint32_t h = a * 2654435761u + b * 40503u + 0x9e3779b9u; h ^= h >> 15; h *= 0x2c1b3c6du; h ^= h >> 12; return h; }- static float u01(uint32_t& s) { s = s * 1664525u + 1013904223u; return (s >> 8) / 16777216.0f; }- float next(uint32_t& s) { return u01(s); }-- // acc = accumulate the random walk (unlocked); locked mode draws statelessly so it stays- // reproducible, in which case Walk falls back to an even draw.- int pickPitch(int dist, uint32_t& s, int range, bool acc = true) {- if (range <= 0) return 0;- float u;- if (dist == 2 && acc) { walk_ += (u01(s) * 2.0f - 1.0f) * 0.34f; walk_ = std::clamp(walk_, -1.0f, 1.0f); u = walk_; }- else if (dist == 1 || dist == 2) u = u01(s) * 2.0f - 1.0f;- else u = ((u01(s) + u01(s) + u01(s)) / 3.0f - 0.5f) * 2.0f; // ~Gauss- return (int)std::lround(u * range);- }- int pickOct(uint32_t& s, float octAmt) { int n = (int)std::lround(octAmt * 2.0f); if (n <= 0) return 0; int k = (int)(u01(s) * (2 * n + 1)) - n; return k * 12; }- float pickVel(uint32_t& s, float velAmt) { return (u01(s) * 2.0f - 1.0f) * velAmt * 0.5f; }- int pickTime(uint32_t& s, float timeAmt) { double ms = (u01(s) * 2.0 - 1.0) * timeAmt * 50.0; return (int)std::lround(ms / 1000.0 * sr_); }- void drawSet(uint32_t s, int dist, int nr, float octAmt, float velAmt, float timeAmt, bool locked) {- barPitch_ = pickPitch(dist, s, nr, !locked); barOct_ = pickOct(s, octAmt); barVel_ = pickVel(s, velAmt); barTime_ = pickTime(s, timeAmt);- if (!locked) rng_ = s;- }- static int foldToMajor(int iv) {- static const int deg[7] = { 0, 2, 4, 5, 7, 9, 11 };- int within = ((iv % 12) + 12) % 12, octs = (iv - within) / 12, best = 0, bd = 99;- for (int d = 0; d < 7; ++d) { int df = std::abs(deg[d] - within); if (df < bd) { bd = df; best = deg[d]; } }- return octs * 12 + best;+ struct Pending { int64_t due; MidiEv ev; };+ static constexpr int kQueue = 512;++ static void push(MidiEv* out, int& nOut, int maxOut, const MidiEv& e) { if (nOut < maxOut) out[nOut++] = e; }+ void enqueue(int64_t due, const MidiEv& e) {+ if (nQueue_ < kQueue) queue_[nQueue_++] = { due, e };}- uint32_t rng_ = 0x9e3779b9u;- float walk_ = 0.0f;- uint32_t noteCounter_ = 0;- int64_t lastBar_ = INT64_MIN;- int barPitch_ = 0, barOct_ = 0, barTime_ = 0; float barVel_ = 0.0f;double sr_ = 44100.0, intBeat_ = 0.0;+ int64_t clock_ = 0;+ uint64_t lastRollKey_ = UINT64_MAX;+ float walk_[4] = { 0, 0, 0, 0 };+ float barD_[4] = { 0, 0, 0, 0 };int8_t offset_[128] = {};uint8_t skipped_[128] = {};+ int32_t delay_[128] = {};+ Pending queue_[kQueue];+ int nQueue_ = 0;+ std::atomic<uint32_t> pass_{0};+ std::atomic<int32_t> bar_{0}, notesIn_{0}, changed_{0}, skippedN_{0}, lastIn_{-1}, lastOut_{-1}, queued_{0};+ std::atomic<float> lastInVel_{0.0f}, lastOutVel_{0.0f}, lastDelayMs_{0.0f};std::atomic<float> p_[kNumParams];};diff --git a/src/native/nota.engine/src/MidiScale.h b/src/native/nota.engine/src/MidiScale.hindex 98e028cb..6f2f6f8e 100644--- a/src/native/nota.engine/src/MidiScale.h+++ b/src/native/nota.engine/src/MidiScale.h@@ -1,21 +1,28 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Nota Scale — a MIDI effect (midiKind 2), reworked to mockup 3b. Snaps incoming pitches-// into a chosen scale, either from a preset or a fully editable 12-note mask (Custom), and-// Folds out-of-scale notes to the Nearest / Down / Up in-scale note. Extras: a Range limiter-// (notes outside pass through), Follow Key (root tracks the notes you play, from a decaying-// pitch-class histogram) and Learn (build the Custom mask from what you just played). The-// last remapped note is published for the card's IN→OUT readout.+// Nota Scale — a MIDI effect (midiKind 2), almanac mockups 1a / 1b. Snaps incoming pitches+// into a scale — a preset (Scale 0..9) or the editable 12-note mask (Scale 10 = Custom,+// stored relative to Root) — folding an out-of-scale note to the Nearest / Down / Up+// in-scale note, then adding Transpose. Extras:+// • Range — only notes inside Range Low..High are snapped; the rest pass through;+// • Follow Key — Root tracks the key of what you play: a decaying pitch-class histogram+// scored against the current scale shape for every root (the best fit wins, with a+// little hysteresis so it doesn't flicker);+// • Learn — a mode: while it's on, notes pass through untouched and every pitch class you+// play is collected into the Custom mask (the first note starts a fresh mask).+// What each key produced is remembered, so its note-off releases exactly that note even if+// the scale changed while it was held; two keys folding onto one note share it by count.+// The editor reads the last IN→OUT pair and a scope (see midiScope) for its live note map.//-// Param layout is APPEND-ONLY: indices 0..2 keep the original Root / Scale / Transpose, so-// old projects load unchanged; 3..19 add the mask, fold, follow-key, range and learn.+// Param layout is APPEND-ONLY: 0..2 Root / Scale / Transpose (the original three), 3..14+// Mask 0..11, 15 Fold, 16 Follow Key, 17 Range Low, 18 Range High, 19 Learn, then (almanac+// rework) 20 View — the editor size (0 = L, 1 = S), UI state.#pragma once#include "MidiDevice.h"#include <algorithm>-#include <cstdio>#include <atomic>#include <cmath>#include <cstdint>@@ -29,20 +36,24 @@ public:PRoot = 0, PScale, PTranspose,PMask0, PMask1, PMask2, PMask3, PMask4, PMask5, PMask6, PMask7, PMask8, PMask9, PMask10, PMask11,PFold, PFollowKey, PRangeLo, PRangeHi, PLearn,+ PView,kNumParams};static constexpr int kNumScales = 10; // 0..9 presets; 10 = Custom (mask params)static constexpr int kCustom = 10;+ static constexpr int kScopeN = 32;MidiScale() {- p_[PRoot].store(0.0f); p_[PScale].store(1.0f); p_[PTranspose].store(0.0f); // C, minor- // Custom mask defaults to major (a sane starting point when the user switches to Custom).+ p_[PRoot].store(0.0f); p_[PScale].store(1.0f); p_[PTranspose].store(0.0f); // C minor — the mockup's opening state+ // The Custom mask starts as major (a sane place to begin editing).static const int maj[] = { 0, 2, 4, 5, 7, 9, 11 };for (int i = 0; i < 12; ++i) p_[PMask0 + i].store(0.0f);for (int d : maj) p_[PMask0 + d].store(1.0f);p_[PFold].store(0.0f); p_[PFollowKey].store(0.0f);- p_[PRangeLo].store(0.0f); p_[PRangeHi].store(127.0f); // full range (matches the old always-quantize)+ p_[PRangeLo].store(0.0f); p_[PRangeHi].store(127.0f);p_[PLearn].store(0.0f);+ p_[PView].store(0.0f);+ resetLive();}int32_t midiKind() const override { return 2; }@@ -50,30 +61,52 @@ public:int32_t paramCount() const override { return kNumParams; }const char* paramName(int32_t i) const override {- switch (i) {- case PRoot: return "Root"; case PScale: return "Scale"; case PTranspose: return "Transpose";- case PFold: return "Fold"; case PFollowKey: return "Follow Key";- case PRangeLo: return "Range Low"; case PRangeHi: return "Range High"; case PLearn: return "Learn";- default:- if (i >= PMask0 && i <= PMask11) { static thread_local char b[12]; std::snprintf(b, sizeof(b), "Mask %d", i - PMask0); return b; }- return "";- }+ static const char* const names[kNumParams] = {+ "Root", "Scale", "Transpose",+ "Mask 0", "Mask 1", "Mask 2", "Mask 3", "Mask 4", "Mask 5", "Mask 6", "Mask 7", "Mask 8", "Mask 9", "Mask 10", "Mask 11",+ "Fold", "Follow Key", "Range Low", "Range High", "Learn",+ "View",+ };+ return (i >= 0 && i < kNumParams) ? names[i] : "";}float paramMin(int32_t i) const override { return i == PTranspose ? -24.0f : 0.0f; }float paramMax(int32_t i) const override {switch (i) {- case PRoot: return 11.0f; case PScale: return kCustom; case PTranspose: return 24.0f;+ case PRoot: return 11.0f; case PScale: return (float)kCustom; case PTranspose: return 24.0f;case PFold: return 2.0f; case PRangeLo: case PRangeHi: return 127.0f;- default: return 1.0f; // masks / follow / learn+ default: return 1.0f; // masks / follow / learn / view}}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 IN→OUT readout for the card (last remapped note-on); -1 = none yet.+ // Live IN→OUT readout for the card (last note-on); -1 = none yet.int32_t midiLastIn() const override { return lastIn_.load(std::memory_order_relaxed); }int32_t midiLastOut() const override { return lastOut_.load(std::memory_order_relaxed); }+ // Editor scope: [0] last in, [1] last out (-1 none), [2] the root in effect (Follow Key+ // moves it), [3] the scale mask in effect (12 bits relative to the root), [4] pitch+ // classes of the keys held now (12 bits, absolute), [5] pitch classes they sound as,+ // [6] learning (0/1), [7] note-ons seen, [8..20) note-ons per input pitch class,+ // [20..32) per output pitch class — counters, so a note shorter than a UI frame still flashes.+ int32_t midiScope(float* out, int32_t maxN) const override {+ if (!out || maxN < 8) return 0;+ out[0] = (float)lastIn_.load(std::memory_order_relaxed);+ out[1] = (float)lastOut_.load(std::memory_order_relaxed);+ out[2] = (float)rootLive_.load(std::memory_order_relaxed);+ out[3] = (float)maskLive_.load(std::memory_order_relaxed);+ out[4] = (float)heldIn_.load(std::memory_order_relaxed);+ out[5] = (float)heldOut_.load(std::memory_order_relaxed);+ out[6] = p_[PLearn].load(std::memory_order_relaxed) >= 0.5f ? 1.0f : 0.0f;+ out[7] = (float)(onCount_.load(std::memory_order_relaxed) & 0xFFFFFF);+ int n = std::min<int32_t>(maxN, kScopeN);+ for (int i = 8; i < n; ++i) {+ int k = i - 8;+ out[i] = (float)((k < 12 ? inHits_[k] : outHits_[k - 12]).load(std::memory_order_relaxed) & 0xFFFFFF);+ }+ return n;+ }+std::shared_ptr<MidiDevice> clone() const override {auto c = std::make_shared<MidiScale>();for (int i = 0; i < kNumParams; ++i) c->p_[i].store(p_[i].load(std::memory_order_relaxed));@@ -81,86 +114,150 @@ public:return c;}- void reset() override { for (auto& h : hist_) h = 0.0f; }+ void reset() override { resetLive(); }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; }+ auto emit = [&](const MidiEv& e, int pitch) {+ if (nOut >= maxOut) return;+ MidiEv o = e; o.pitch = pitch; out[nOut++] = o;+ };- // Learn (one-shot): build the Custom mask from the recent-input histogram.- if (p_[PLearn].load(std::memory_order_relaxed) >= 0.5f) {- doLearn(); p_[PLearn].store(0.0f, std::memory_order_relaxed);- }- int root = std::clamp((int)std::lround(p_[PRoot].load(std::memory_order_relaxed)), 0, 11);- // Follow Key: root tracks the dominant recent pitch class.- if (p_[PFollowKey].load(std::memory_order_relaxed) >= 0.5f) {- int dom = dominantPc(); if (dom >= 0) { root = dom; p_[PRoot].store((float)dom, std::memory_order_relaxed); }- }- const uint16_t bits = effectiveMask();- const int fold = std::clamp((int)std::lround(p_[PFold].load(std::memory_order_relaxed)), 0, 2);- const int tr = (int)std::lround(p_[PTranspose].load(std::memory_order_relaxed));- const int lo = std::clamp((int)std::lround(p_[PRangeLo].load(std::memory_order_relaxed)), 0, 127);- const int hi = std::clamp((int)std::lround(p_[PRangeHi].load(std::memory_order_relaxed)), 0, 127);+ const bool learn = p_[PLearn].load(std::memory_order_relaxed) >= 0.5f;+ if (learn && !learnWas_) learnFresh_ = true; // a new Learn pass starts a fresh mask+ learnWas_ = learn;+ const bool follow = p_[PFollowKey].load(std::memory_order_relaxed) >= 0.5f && !learn;+ const bool bypass = bypassed();for (int i = 0; i < nIn; ++i) {const MidiEv& e = in[i];+ if (e.pitch < 0 || e.pitch > 127) continue;+ if (!e.on) { release(e, emit); continue; }+ if (outFor_[e.pitch] >= 0) release({ e.off, false, e.pitch, 0.0f }, emit); // a retriggered key lets go first+int p = e.pitch;- if (bits && e.pitch >= std::min(lo, hi) && e.pitch <= std::max(lo, hi))- p = quantize(e.pitch, root, bits, fold) + tr;- if (p < 0 || p > 127) continue;- if (nOut < maxOut) out[nOut++] = { e.off, e.on, p, e.vel };- if (e.on) {- lastIn_.store(e.pitch, std::memory_order_relaxed);- lastOut_.store(p, std::memory_order_relaxed);- for (auto& h : hist_) h *= 0.9f; // decay- hist_[((e.pitch % 12) + 12) % 12] += 1.0f; // remember what was played+ if (!bypass) {+ if (learn) learnNote(e.pitch);+ else {+ if (follow) followNote(e.pitch);+ p = map(e.pitch);+ }}+ if (p < 0 || p > 127) continue;+ outFor_[e.pitch] = (int8_t)p;+ ++outRef_[p];+ emit(e, p);+ lastIn_.store(e.pitch, std::memory_order_relaxed);+ lastOut_.store(p, std::memory_order_relaxed);+ onCount_.fetch_add(1, std::memory_order_relaxed);+ inHits_[e.pitch % 12].fetch_add(1, std::memory_order_relaxed);+ outHits_[p % 12].fetch_add(1, std::memory_order_relaxed);}+ publish();}private:static uint16_t presetMask(int sc) {- static const uint16_t m[kNumScales] = {- 2741, 1453, 2477, 1709, 1451, 2773, 1717, 661, 1193, 4095,- // major, natural minor, harmonic minor, dorian, phrygian, lydian, mixolydian, penta maj, penta min, chromatic- };+ // major, natural minor, harmonic minor, dorian, phrygian, lydian, mixolydian, penta maj, penta min, chromatic+ static const uint16_t m[kNumScales] = { 2741, 1453, 2477, 1709, 1451, 2773, 1717, 661, 1193, 4095 };return m[std::clamp(sc, 0, kNumScales - 1)];}- uint16_t effectiveMask() const {+ int root() const { return ((int)std::lround(p_[PRoot].load(std::memory_order_relaxed)) % 12 + 12) % 12; }+ uint16_t mask() const {int sc = (int)std::lround(p_[PScale].load(std::memory_order_relaxed));if (sc < kCustom) return presetMask(sc);uint16_t m = 0;for (int i = 0; i < 12; ++i) if (p_[PMask0 + i].load(std::memory_order_relaxed) >= 0.5f) m |= (uint16_t)(1 << i);return m;}++ // The pitch a note-on plays as: snapped (inside the range, with a non-empty scale), then transposed.+ int map(int pitch) const {+ const int lo = std::clamp((int)std::lround(p_[PRangeLo].load(std::memory_order_relaxed)), 0, 127);+ const int hi = std::clamp((int)std::lround(p_[PRangeHi].load(std::memory_order_relaxed)), 0, 127);+ if (pitch < std::min(lo, hi) || pitch > std::max(lo, hi)) return pitch;+ const uint16_t bits = mask();+ const int fold = std::clamp((int)std::lround(p_[PFold].load(std::memory_order_relaxed)), 0, 2);+ const int tr = (int)std::lround(p_[PTranspose].load(std::memory_order_relaxed));+ return (bits ? quantize(pitch, root(), bits, fold) : pitch) + tr;+ }static int quantize(int pitch, int root, uint16_t bits, int fold) {- int pc = ((pitch - root) % 12 + 12) % 12;- auto has = [&](int x) { return (bits & (1 << (((x) % 12 + 12) % 12))) != 0; };+ const int pc = ((pitch - root) % 12 + 12) % 12;+ auto has = [&](int x) { return (bits & (1 << ((x % 12 + 12) % 12))) != 0; };if (fold == 1) { for (int d = 0; d < 12; ++d) if (has(pc - d)) return pitch - d; } // Downelse if (fold == 2) { for (int d = 0; d < 12; ++d) if (has(pc + d)) return pitch + d; } // Up- else { for (int d = 0; d < 7; ++d) { if (has(pc + d)) return pitch + d; if (has(pc - d)) return pitch - d; } } // Nearest+ else { for (int d = 0; d < 7; ++d) { if (has(pc + d)) return pitch + d; if (has(pc - d)) return pitch - d; } } // Nearest (a tie goes up)return pitch;}- int dominantPc() const {- int best = -1; float bv = 1e-4f;- for (int i = 0; i < 12; ++i) if (hist_[i] > bv) { bv = hist_[i]; best = i; }- return best;++ template <class Emit> void release(const MidiEv& e, Emit& emit) {+ const int p = outFor_[e.pitch];+ if (p < 0) { emit(e, e.pitch); return; } // never mapped (e.g. held before the device) — pass it on+ outFor_[e.pitch] = -1;+ if (outRef_[p] > 0 && --outRef_[p] == 0) emit(e, p);}- void doLearn() {- float mx = 0; for (float h : hist_) mx = std::max(mx, h);- if (mx < 1e-4f) return; // nothing played — keep the current mask- int root = std::clamp((int)std::lround(p_[PRoot].load(std::memory_order_relaxed)), 0, 11);- for (int i = 0; i < 12; ++i) {- int rel = ((i - root) % 12 + 12) % 12; // store relative to root- p_[PMask0 + rel].store(hist_[i] > 0.12f * mx ? 1.0f : 0.0f, std::memory_order_relaxed);++ void learnNote(int pitch) {+ const int r = root();+ if (learnFresh_) {+ for (int i = 0; i < 12; ++i) p_[PMask0 + i].store(0.0f, std::memory_order_relaxed);+ p_[PScale].store((float)kCustom, std::memory_order_relaxed);+ learnFresh_ = false;}- p_[PScale].store((float)kCustom, std::memory_order_relaxed);+ p_[PMask0 + ((pitch - r) % 12 + 12) % 12].store(1.0f, std::memory_order_relaxed);}- float hist_[12] = {};- std::atomic<int32_t> lastIn_{-1}, lastOut_{-1};- std::atomic<float> p_[kNumParams];+ void followNote(int pitch) {+ for (auto& h : hist_) h *= 0.92f;+ hist_[pitch % 12] += 1.0f;+ const uint16_t bits = mask();+ if (!bits || bits == 0xFFF) return; // chromatic / empty: every root fits alike+ auto score = [&](int r) {+ float s = 0.0f;+ for (int pc = 0; pc < 12; ++pc) {+ const int rel = ((pc - r) % 12 + 12) % 12;+ s += hist_[pc] * ((bits & (1 << rel)) ? (rel == 0 ? 1.6f : rel == 7 && (bits & 0x80) ? 1.25f : 1.0f) : -0.8f);+ }+ return s;+ };+ const int cur = root();+ int best = cur; float bs = score(cur);+ for (int r = 0; r < 12; ++r) { float s = score(r); if (s > bs + 0.35f) { bs = s; best = r; } }+ if (best != cur) p_[PRoot].store((float)best, std::memory_order_relaxed);+ }++ void publish() {+ uint16_t hin = 0, hout = 0;+ for (int k = 0; k < 128; ++k)+ if (outFor_[k] >= 0) { hin |= (uint16_t)(1 << (k % 12)); hout |= (uint16_t)(1 << (outFor_[k] % 12)); }+ heldIn_.store(hin, std::memory_order_relaxed);+ heldOut_.store(hout, std::memory_order_relaxed);+ rootLive_.store(root(), std::memory_order_relaxed);+ maskLive_.store(mask(), std::memory_order_relaxed);+ }++ void resetLive() {+ for (auto& o : outFor_) o = -1;+ for (auto& r : outRef_) r = 0;+ for (auto& h : hist_) h = 0.0f;+ learnFresh_ = p_[PLearn].load(std::memory_order_relaxed) >= 0.5f;+ heldIn_.store(0, std::memory_order_relaxed);+ heldOut_.store(0, std::memory_order_relaxed);+ }++ // audio-thread state+ int8_t outFor_[128]; // input key → the pitch it sounds as (-1 = not held)+ uint8_t outRef_[128]; // output pitch → how many held keys share it+ float hist_[12] = {};+ bool learnWas_ = false, learnFresh_ = false;++ // telemetry+ std::atomic<int32_t> lastIn_{-1}, lastOut_{-1};+ std::atomic<int32_t> rootLive_{0}, maskLive_{1453}, heldIn_{0}, heldOut_{0};+ std::atomic<uint32_t> onCount_{0};+ std::atomic<uint32_t> inHits_[12] = {}, outHits_[12] = {};+ std::atomic<float> p_[kNumParams];};} // namespace notadiff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 40de501c..b60abe2f 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -6530,87 +6530,353 @@ Console.WriteLine("-- Nota Chord --");}}-// ===================== Nota Scale (MIDI kind 2) rework =====================+// ===================== Nota Scale (MIDI kind 2) — almanac rework =====================Console.WriteLine("-- Nota Scale --");{using var e = new NotaEngine();e.SetBpm(120); e.SetTimeSignature(4, 4);int t = e.AddInstrumentTrack();int m = e.AddMidiEffect(t, 2);- Check(m == 0 && e.MidiEffectName(t, 0) == "Nota Scale", "add Nota Scale");+ Check(m == 0 && e.MidiEffectName(t, 0) == "Nota Scale" && e.MidiEffectKind(t, 0) == 2, "add Nota Scale");int pc = e.MidiEffectParamCount(t, 0);- Check(pc == 20, $"Nota Scale exposes 20 params (got {pc})");- var pnames = new System.Collections.Generic.HashSet<string>();- for (int i = 0; i < pc; i++) pnames.Add(e.MidiEffectParamName(t, 0, i));- Check(pnames.Contains("Fold") && pnames.Contains("Follow Key") && pnames.Contains("Range Low")- && pnames.Contains("Range High") && pnames.Contains("Learn") && pnames.Contains("Mask 0") && pnames.Contains("Mask 11"),- "mockup-3b params present (Fold / Follow Key / Range / Learn / Mask 0-11)");-- // C major, Nearest fold: an out-of-scale C#4 (61) snaps into the scale, and the last- // remapped note-on is published for the card's IN→OUT readout.- SetByName(e, t, 0, "Root", 0f); SetByName(e, t, 0, "Scale", 0f); SetByName(e, t, 0, "Fold", 0f);- e.AddMidiClip(t, 0.0, 4.0);- e.SetClipNotes(t, 0, new[] { new NotaNote(61, 0.0, 2.0, 0.9f) });- var scbuf = new float[12000 * 2]; e.Seek(0); e.Play(); e.RenderOffline(scbuf, 12000); e.StopTransport();- int li = e.MidiEffectLastIn(t, 0), lo = e.MidiEffectLastOut(t, 0);- int[] cmaj = { 0, 2, 4, 5, 7, 9, 11 };- Check(li == 61 && lo >= 0 && System.Array.IndexOf(cmaj, ((lo % 12) + 12) % 12) >= 0, $"quantizes out-of-scale note into scale (IN {li} OUT {lo})");+ Check(pc == 21, $"Nota Scale exposes 21 params (got {pc})");+ string[] expect = { "Root", "Scale", "Transpose", "Mask 0", "Mask 11", "Fold", "Follow Key", "Range Low", "Range High", "Learn", "View" };+ int[] at = { 0, 1, 2, 3, 14, 15, 16, 17, 18, 19, 20 };+ bool layout = true; for (int i = 0; i < expect.Length; i++) layout &= e.MidiEffectParamName(t, 0, at[i]) == expect[i];+ Check(layout, "param layout is append-only (Root/Scale/Transpose, Mask 0-11, Fold … Learn, then View)");+ Check(GetByName(e, t, 0, "Scale") == 1f && GetByName(e, t, 0, "Root") == 0f && GetByName(e, t, 0, "View") == 0f, "defaults: C minor, card L");++ // Play a short run of notes, return every output note-on (read back through the IN→OUT telemetry,+ // one note per 1/8 so each block sees at most one note-on).+ e.AddMidiClip(t, 0.0, 16.0);+ var flush = new float[256 * 2];+ void Stop() { e.StopTransport(); e.RenderOffline(flush, 256); } // a stopped block flushes held notes (play → stop edge)+ int[] Run(params int[] ins)+ {+ Stop();+ e.SetClipNotes(t, 0, ins.Select((p, i) => new NotaNote(p, i * 0.5, 0.25, 0.9f)).ToArray());+ var outs = new List<int>(); var buf = new float[256 * 2]; int seen = 0;+ var sc = new float[32];+ e.Seek(0); e.Play();+ for (int blk = 0; blk < 44100 * (ins.Length * 0.25 + 0.3) / 256 && outs.Count < ins.Length; blk++)+ {+ e.RenderOffline(buf, 256);+ e.MidiEffectScope(t, 0, sc);+ if ((int)sc[7] != seen) { seen = (int)sc[7]; outs.Add(e.MidiEffectLastOut(t, 0)); }+ }+ e.StopTransport();+ return outs.ToArray();+ }+ string J(IEnumerable<int> a) => string.Join(",", a);++ // C major, Nearest (a tie goes up) / Down / Up on C#4 D#4 F#4 A#4.+ SetByName(e, t, 0, "Scale", 0f);+ var near = Run(61, 63, 66, 70);+ Check(J(near) == "62,64,67,71", $"C major Nearest folds C# D# F# A# → D E G B (got {J(near)})");+ SetByName(e, t, 0, "Fold", 1f);+ var down = Run(61, 63, 66, 70);+ Check(J(down) == "60,62,65,69", $"Fold Down → C D F A (got {J(down)})");+ SetByName(e, t, 0, "Fold", 2f);+ var up = Run(61, 63, 66, 70);+ Check(J(up) == "62,64,67,71", $"Fold Up → D E G B (got {J(up)})");+ SetByName(e, t, 0, "Fold", 0f);++ // Root + Transpose; Range passes notes outside through.+ SetByName(e, t, 0, "Root", 2f); SetByName(e, t, 0, "Scale", 1f); // D minor: D E F G A A# C+ var dm = Run(61, 66, 71);+ Check(J(dm) == "62,67,72", $"D minor snaps C# F# B → D G C, ties going up (got {J(dm)})");+ SetByName(e, t, 0, "Transpose", 12f);+ Check(J(Run(61)) == "74", "Transpose adds after snapping");+ SetByName(e, t, 0, "Transpose", 0f);+ SetByName(e, t, 0, "Range Low", 60f); SetByName(e, t, 0, "Range High", 64f);+ var rg = Run(61, 66);+ Check(J(rg) == "62,66", $"Range: F#4 (outside 60..64) passes through (got {J(rg)})");+ SetByName(e, t, 0, "Range Low", 0f); SetByName(e, t, 0, "Range High", 127f);++ // Custom mask (relative to the root) + an empty mask passes everything.+ SetByName(e, t, 0, "Root", 0f); SetByName(e, t, 0, "Scale", 10f);+ for (int i = 0; i < 12; i++) SetByName(e, t, 0, $"Mask {i}", i == 0 || i == 7 ? 1f : 0f);+ var c5 = Run(62, 65, 69);+ Check(J(c5) == "60,67,67", $"Custom root + fifth: D F A → C G G (got {J(c5)})");+ for (int i = 0; i < 12; i++) SetByName(e, t, 0, $"Mask {i}", 0f);+ Check(J(Run(61, 66)) == "61,66", "an empty Custom scale passes notes through");++ // Learn: a fresh Custom scale from what's played; notes pass untouched while learning.+ SetByName(e, t, 0, "Learn", 1f);+ var learned = Run(62, 65, 69, 62);+ SetByName(e, t, 0, "Learn", 0f);+ bool lm = true; for (int i = 0; i < 12; i++) lm &= GetByName(e, t, 0, $"Mask {i}") == (i is 2 or 5 or 9 ? 1f : 0f);+ Check(J(learned) == "62,65,69,62" && lm && GetByName(e, t, 0, "Scale") == 10f, $"Learn collects D F A into Custom, passing them through (got {J(learned)})");+ Check(J(Run(64)) == "65", "the learned scale snaps E → F");- // Custom mask: switch to Custom + set an empty-ish mask → different remap vs the preset.- SetByName(e, t, 0, "Scale", 10f); // Custom+ // Follow Key: a G-major line moves a C major scale's root to G.for (int i = 0; i < 12; i++) SetByName(e, t, 0, $"Mask {i}", 0f);- SetByName(e, t, 0, "Mask 0", 1f); SetByName(e, t, 0, "Mask 7", 1f); // only root + fifth- e.Seek(0); e.Play(); e.RenderOffline(scbuf, 12000); e.StopTransport();- int lo2 = e.MidiEffectLastOut(t, 0);- Check(lo2 >= 0 && (((lo2 % 12) + 12) % 12 == 0 || ((lo2 % 12) + 12) % 12 == 7), $"custom two-note scale folds to root/fifth (OUT {lo2})");+ SetByName(e, t, 0, "Scale", 0f); SetByName(e, t, 0, "Root", 0f); SetByName(e, t, 0, "Follow Key", 1f);+ Run(67, 71, 74, 66, 67, 71, 74, 66, 62, 67);+ Check(GetByName(e, t, 0, "Root") == 7f, $"Follow Key finds G from a G-major line (root {GetByName(e, t, 0, "Root")})");+ SetByName(e, t, 0, "Follow Key", 0f); SetByName(e, t, 0, "Root", 0f);+ // Note-offs follow the note-on even when the scale changes while the key is held.+ {+ Stop();+ e.SetClipNotes(t, 0, new[] { new NotaNote(61, 0.0, 2.0, 0.9f) });+ var sc = new float[32]; var hb = new float[512 * 2];+ e.Seek(0); e.Play();+ for (int i = 0; i < 20; i++) e.RenderOffline(hb, 512);+ e.MidiEffectScope(t, 0, sc);+ bool heldD = ((int)sc[5] & (1 << 2)) != 0 && ((int)sc[4] & (1 << 1)) != 0;+ SetByName(e, t, 0, "Fold", 1f); // now C# would fold to C…+ for (int i = 0; i < 200; i++) e.RenderOffline(hb, 512); // …past the note's end+ e.MidiEffectScope(t, 0, sc);+ e.StopTransport();+ Check(heldD && (int)sc[4] == 0 && (int)sc[5] == 0, $"held C# sounds as D and releases it after a fold change (held in {(int)sc[4]} out {(int)sc[5]})");+ SetByName(e, t, 0, "Fold", 0f);+ }++ // Bypass passes notes; telemetry counts note-ons per pitch class.+ e.SetMidiEffectBypassed(t, 0, true);+ Check(J(Run(61)) == "61", "bypassed Scale passes notes through");+ e.SetMidiEffectBypassed(t, 0, false);++ // It still makes sound, and duplicating the track clones the scale.+ SetByName(e, t, 0, "Scale", 10f);+ for (int i = 0; i < 12; i++) SetByName(e, t, 0, $"Mask {i}", i == 0 || i == 7 ? 1f : 0f);+ SetByName(e, t, 0, "View", 1f);+ e.SetClipNotes(t, 0, new[] { new NotaNote(61, 0.0, 2.0, 0.9f) });+ var scbuf = new float[12000 * 2]; e.Seek(0); e.Play(); e.RenderOffline(scbuf, 12000); e.StopTransport();+ bool fin = true; foreach (var x in scbuf) if (!float.IsFinite(x)) { fin = false; break; }+ Check(fin && Rms(scbuf, 12000) > 0.001f, "Scale → instrument renders audible, finite audio");int t2 = e.DuplicateTrack(t);- Check(t2 > 0 && Math.Abs(GetByName(e, t2, 0, "Mask 7") - 1f) < 1e-3, "duplicate track clones Scale custom mask");+ Check(t2 > 0 && GetByName(e, t2, 0, "Mask 7") == 1f && GetByName(e, t2, 0, "Mask 4") == 0f && GetByName(e, t2, 0, "View") == 1f,+ "duplicate track clones the Custom mask and card size");++ // Automation drives Root.+ {+ int lane = e.AddAutomationLane(t, AutomationTarget.MidiDeviceParam, 0, 0);+ e.SetAutomationPoints(t, lane, new[] { new AutomationPoint(0, 5f, 0), new AutomationPoint(16, 5f, 0) });+ var ab = new float[1024 * 2]; e.Seek(0); e.Play(); e.RenderOffline(ab, 1024); e.StopTransport();+ Check(Math.Abs(GetByName(e, t, 0, "Root") - 5f) < 0.01f, $"automation drives Root (got {GetByName(e, t, 0, "Root")})");+ e.RemoveAutomationLane(t, lane);+ }++ // MCP: named read / write.+ {+ var mcp = new Nota.Mcp.Tools.MidiFxTools(e, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());+ mcp.SetScale(t, 0, root: "A", scale: "minor", fold: "down", rangeLow: 36, view: "L").GetAwaiter().GetResult();+ var st = mcp.GetScale(t, 0).GetAwaiter().GetResult();+ Check(st.Root == "A" && st.Scale == "minor" && J(st.Degrees) == "0,2,3,5,7,8,10" && string.Join(" ", st.Notes) == "A B C D E F G"+ && st.Fold == "down" && st.RangeLow == 36 && st.View == "L" && st.FoldMap[1] == "C#→C", $"MCP get/set_scale (notes {string.Join(" ", st.Notes)}, C# {st.FoldMap[1]})");+ mcp.SetScaleNote(t, 0, "G#", true).GetAwaiter().GetResult();+ st = mcp.GetScale(t, 0).GetAwaiter().GetResult();+ Check(st.Scale == "custom" && string.Join(" ", st.Notes) == "A B C D E F G G#", $"MCP set_scale_note turns the scale Custom ({string.Join(" ", st.Notes)})");+ mcp.SetScale(t, 0, notes: new[] { "D", "F", "A" }).GetAwaiter().GetResult();+ st = mcp.GetScale(t, 0).GetAwaiter().GetResult();+ Check(J(st.Degrees) == "0,5,8" && st.Scale == "custom", $"MCP notes → Custom degrees relative to the root ({J(st.Degrees)})");+ mcp.SetScale(t, 0, root: "C", scale: "major", fold: "nearest", rangeLow: 0).GetAwaiter().GetResult();+ }++ // A project from before View loads as the L card; a factory preset keeps the card size.+ {+ 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 == 2).MidiEffects[0];+ md.Params = md.Params.Take(20).ToArray();+ using var e2 = new NotaEngine();+ ProjectService.Apply(doc, e2, Path.GetTempPath());+ int lt = -1;+ for (int i = 0; e2.TryGetTrackInfo(i, out var ti); i++) if (e2.TrackMidiEffectCount(ti.Id) > 0 && e2.MidiEffectKind(ti.Id, 0) == 2) { lt = ti.Id; break; }+ Check(lt > 0 && GetByName(e2, lt, 0, "View") == 0f && GetByName(e2, lt, 0, "Scale") == 0f, "a pre-View Scale project loads (card L)");+ }+ {+ var cat = new FactoryPresetCatalog();+ var mine = cat.All().Where(p => p.IsMidiEffect && p.BuiltinKind == 2).ToList();+ Check(mine.Count >= 25, $"Nota Scale 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 Scale preset param name exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");+ SetByName(e, t, 0, "View", 1f);+ var off = new System.Collections.Generic.List<string>();+ e.SetClipNotes(t, 0, new[] { new NotaNote(61, 0.0, 1.0, 0.9f) });+ 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[12000 * 2]; e.Seek(0); e.Play(); e.RenderOffline(pb, 12000); 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, 12000) < 0.001f) off.Add(p.DisplayName);+ }+ Check(off.Count == 0, $"every Scale 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 blues = mine.First(p => p.DisplayName == "A Blues");+ cat.ApplyInPlace(e, blues.Id, t, 0);+ Check(GetByName(e, t, 0, "Root") == 9f && GetByName(e, t, 0, "Scale") == 10f && GetByName(e, t, 0, "Mask 6") == 1f && GetByName(e, t, 0, "Mask 4") == 0f,+ "A Blues preset sets root A and its Custom degrees");+ }}-// ===================== Nota Length (MIDI kind 3) rework =====================+// ===================== Nota Length (MIDI kind 3) — almanac rework =====================Console.WriteLine("-- Nota Length --");{+ static float RmsRange(float[] b, int from, int to) { double sum = 0; for (int i = from * 2; i < to * 2; i++) sum += b[i] * (double)b[i]; return (float)Math.Sqrt(sum / Math.Max(1, (to - from) * 2)); }using var e = new NotaEngine();e.SetBpm(120); e.SetTimeSignature(4, 4);int t = e.AddInstrumentTrack();int m = e.AddMidiEffect(t, 3);- Check(m == 0 && e.MidiEffectName(t, 0) == "Nota Length", $"add Nota Length (got '{e.MidiEffectName(t, 0)}')");+ Check(m == 0 && e.MidiEffectName(t, 0) == "Nota Length" && e.MidiEffectKind(t, 0) == 3, $"add Nota Length (got '{e.MidiEffectName(t, 0)}')");int pc = e.MidiEffectParamCount(t, 0);- Check(pc == 11, $"Nota Length exposes 11 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("Mode") && pn.Contains("Ms") && pn.Contains("Percent") && pn.Contains("Trigger")- && pn.Contains("Vel to Len") && pn.Contains("Key to Len") && pn.Contains("Random")- && pn.Contains("Legato") && pn.Contains("Clip Limit"), "mockup-3b params present");+ Check(pc == 13, $"Nota Length exposes 13 params (got {pc})");+ string[] expect = { "Rate", "Gate", "Mode", "Ms", "Percent", "Trigger", "Vel to Len", "Key to Len", "Random", "Legato", "Clip Limit", "Division", "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 (… Clip Limit, then Division / View)");+ Check(e.MidiEffectParamMin(t, 0, 6) == -1f && e.MidiEffectParamMin(t, 0, 7) == -1f && e.MidiEffectParamMax(t, 0, 11) == 7f,+ "Vel / Key to Len are bipolar, Division spans 8 values");+ Check(GetByName(e, t, 0, "Mode") == 0f && GetByName(e, t, 0, "Division") == 2f && GetByName(e, t, 0, "Gate") == 1f, "defaults: Sync 1/8");++ // The forced length, read back from the telemetry: [3] last out pitch, [4] its length in beats.+ var sc = new float[8];+ e.AddMidiClip(t, 0.0, 8.0);+ float OutLen(NotaNote[] ns, double seconds)+ {+ e.StopTransport();+ e.SetClipNotes(t, 0, ns);+ var buf = new float[2048 * 2]; e.Seek(0); e.Play();+ int blocks = (int)Math.Ceiling(seconds * 44100 / 2048); // offline renders at 44.1 kHz+ for (int b = 0; b < blocks; b++) e.RenderOffline(buf, 2048);+ e.StopTransport();+ return e.MidiEffectScope(t, 0, sc) >= 5 ? sc[4] : -1;+ }+ bool Near(float v, double want) => Math.Abs(v - want) < 0.02;+ var held3 = new[] { new NotaNote(60, 0.0, 3.0, 64f / 127f) }; // vel 64: the velocity modifier is neutral+ SetByName(e, t, 0, "Division", 3f);+ float l = OutLen(held3, 2.0); Check(Near(l, 1.0), $"Sync 1/4 forces a 3-beat note to 1 beat (got {l:0.000})");+ SetByName(e, t, 0, "Division", 6f);+ l = OutLen(held3, 2.0); Check(Near(l, 0.75), $"Sync 1/8. → 0.75 beat (got {l:0.000})");+ SetByName(e, t, 0, "Division", 7f);+ l = OutLen(held3, 2.0); Check(Near(l, 2.0 / 3), $"Sync 1/4T → ⅔ beat (got {l:0.000})");+ SetByName(e, t, 0, "Mode", 1f); SetByName(e, t, 0, "Ms", 250f);+ l = OutLen(held3, 2.0); Check(Near(l, 0.5), $"ms 250 at 120 BPM → ½ beat (got {l:0.000})");+ SetByName(e, t, 0, "Mode", 2f); SetByName(e, t, 0, "Percent", 50f);+ l = OutLen(new[] { new NotaNote(60, 0.0, 2.0, 64f / 127f) }, 2.0); Check(Near(l, 1.0), $"Gate 50 % of a 2-beat note → 1 beat (got {l:0.000})");+ SetByName(e, t, 0, "Percent", 25f);+ l = OutLen(new[] { new NotaNote(60, 0.0, 2.0, 64f / 127f) }, 2.0); Check(Near(l, 0.5), $"Gate 25 % shortens a clip note (its length rides on the note-on) → ½ beat (got {l:0.000})");+ SetByName(e, t, 0, "Percent", 150f);+ l = OutLen(new[] { new NotaNote(60, 0.0, 1.0, 64f / 127f) }, 2.0); Check(Near(l, 1.5), $"Gate 150 % of a 1-beat note → 1.5 beats (got {l:0.000})");++ // Bipolar modifiers: + makes loud / low notes longer, − the opposite.+ SetByName(e, t, 0, "Mode", 0f); SetByName(e, t, 0, "Division", 3f);+ SetByName(e, t, 0, "Vel to Len", 1f);+ l = OutLen(new[] { new NotaNote(60, 0.0, 3.0, 1f) }, 2.5); Check(Near(l, 1 + 63.0 / 64), $"Vel → Len +100 %: vel 127 nearly doubles (got {l:0.000})");+ SetByName(e, t, 0, "Vel to Len", -0.5f);+ l = OutLen(new[] { new NotaNote(60, 0.0, 3.0, 1f) }, 2.5); Check(Near(l, 1 - 0.5 * 63 / 64), $"Vel → Len −50 %: loud notes shorter (got {l:0.000})");+ SetByName(e, t, 0, "Vel to Len", 0f);+ SetByName(e, t, 0, "Key to Len", 1f);+ l = OutLen(new[] { new NotaNote(48, 0.0, 3.0, 64f / 127f) }, 2.5); Check(Near(l, 1.5), $"Key → Len +100 %: C3 lasts 1.5× (got {l:0.000})");+ l = OutLen(new[] { new NotaNote(72, 0.0, 3.0, 64f / 127f) }, 2.5); Check(Near(l, 0.5), $"Key → Len +100 %: C5 lasts 0.5× (got {l:0.000})");+ SetByName(e, t, 0, "Key to Len", 0f);++ // Random spreads within ±amount.+ SetByName(e, t, 0, "Random", 0.5f);+ var rl = new System.Collections.Generic.List<float>();+ for (int k = 0; k < 6; k++) rl.Add(OutLen(held3, 2.0));+ Check(rl.All(x => x >= 0.49 && x <= 1.51) && rl.Max() - rl.Min() > 0.01, $"Random ±50 % spreads 0.5..1.5 beats ({string.Join(" ", rl.Select(x => x.ToString("0.00")))})");+ SetByName(e, t, 0, "Random", 0f);++ // Clip length limit: a 1/2 note from beat 3.5 stops at the bar line.+ SetByName(e, t, 0, "Division", 4f); SetByName(e, t, 0, "Clip Limit", 1f);+ l = OutLen(new[] { new NotaNote(60, 3.5, 3.0, 64f / 127f) }, 3.0); Check(Near(l, 0.5), $"Clip length limit cuts at the bar line (got {l:0.000})");+ SetByName(e, t, 0, "Clip Limit", 0f);+ l = OutLen(new[] { new NotaNote(60, 3.5, 3.0, 64f / 127f) }, 3.5); Check(Near(l, 2.0), $"without Clip the note crosses the bar (got {l:0.000})");++ // Legato: each note lasts until the next one starts.+ SetByName(e, t, 0, "Division", 1f); SetByName(e, t, 0, "Legato", 1f);+ l = OutLen(new[] { new NotaNote(60, 0.0, 0.2, 64f / 127f), new NotaNote(64, 1.0, 0.2, 64f / 127f) }, 0.65);+ Check(Near(l, 1.0) && (int)sc[3] == 60, $"Legato stretches a 1/16 to the next note (C4 {l:0.000} beats)");+ SetByName(e, t, 0, "Legato", 0f);++ // Start from note-off: the note fires on release and nothing sounds while the key is held.+ SetByName(e, t, 0, "Division", 3f); SetByName(e, t, 0, "Trigger", 1f);+ {+ e.StopTransport();+ e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 1.0, 0.9f) });+ var quiet = new float[2048 * 2]; for (int b = 0; b < 60; b++) e.RenderOffline(quiet, 2048); // let earlier tails die away+ const int beat = 22050; // 1 beat at 120 BPM, 44.1 kHz offline+ var ob = new float[beat * 3 * 2]; var blk = new float[1050 * 2];+ e.Seek(0); e.Play();+ for (int o = 0; o < beat * 3; o += 1050) { e.RenderOffline(blk, 1050); Array.Copy(blk, 0, ob, o * 2, 1050 * 2); }+ e.StopTransport();+ float held = RmsRange(ob, 0, beat - 256), after = RmsRange(ob, beat + 512, 2 * beat);+ e.MidiEffectScope(t, 0, sc);+ Check(held < 1e-5f && after > 0.001f && Near(sc[4], 1.0), $"note-off start: silent while held ({held:E1}), sounds after release ({after:0.0000}), 1 beat long");+ }+ SetByName(e, t, 0, "Trigger", 0f);- // A long note forced to a short synced length differs from bypass (note cut short).- e.AddMidiClip(t, 0.0, 4.0);- e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 3.0, 0.9f) }); // held 3 beats- SetByName(e, t, 0, "Mode", 0f); SetByName(e, t, 0, "Rate", 0f); SetByName(e, t, 0, "Gate", 1f); // 1/16- var on = new float[40000 * 2]; e.Seek(0); e.Play(); e.RenderOffline(on, 40000); e.StopTransport();- e.SetMidiEffectBypassed(t, 0, true);- var off = new float[40000 * 2]; e.Seek(0); e.Play(); e.RenderOffline(off, 40000); e.StopTransport();- e.SetMidiEffectBypassed(t, 0, false);- double diff = 0; for (int i = 0; i < 40000 * 2; i++) { double d = on[i] - off[i]; diff += d * d; }- Check(Math.Sqrt(diff / (40000 * 2)) > 0.003, "Sync mode forces (shortens) the note vs bypass");+ // Bypass mid-note releases what the device still holds.+ {+ SetByName(e, t, 0, "Division", 5f);+ e.StopTransport();+ e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 0.25, 0.9f) });+ var hb = new float[2048 * 2]; e.Seek(0); e.Play();+ for (int b = 0; b < 8; b++) e.RenderOffline(hb, 2048);+ e.SetMidiEffectBypassed(t, 0, true);+ for (int b = 0; b < 80; b++) e.RenderOffline(hb, 2048);+ e.StopTransport(); e.SetMidiEffectBypassed(t, 0, false);+ Check(Rms(hb, 2048) < 1e-4f, $"bypass mid-note leaves no stuck notes (tail RMS {Rms(hb, 2048):E1})");+ }// Every mode + the note-off trigger renders finite + audible.+ e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 3.0, 0.9f) });void RenderFinite(string tag, Action cfg){cfg();var b = new float[40000 * 2]; e.Seek(0); e.Play(); e.RenderOffline(b, 40000); e.StopTransport();- bool fin = true; foreach (var s in b) if (!float.IsFinite(s) || Math.Abs(s) > 8f) { fin = false; break; }+ bool fin = true; foreach (var x in b) if (!float.IsFinite(x) || Math.Abs(x) > 8f) { fin = false; break; }Check(fin && Rms(b, 40000) > 0.0005f, $"{tag} renders finite + audible");}RenderFinite("ms mode", () => { SetByName(e, t, 0, "Mode", 1f); SetByName(e, t, 0, "Ms", 120f); });RenderFinite("Gate% mode", () => { SetByName(e, t, 0, "Mode", 2f); SetByName(e, t, 0, "Percent", 50f); });- RenderFinite("note-off trigger", () => { SetByName(e, t, 0, "Mode", 0f); SetByName(e, t, 0, "Trigger", 1f); });- RenderFinite("modifiers + legato", () => { SetByName(e, t, 0, "Trigger", 0f); SetByName(e, t, 0, "Vel to Len", 0.6f); SetByName(e, t, 0, "Random", 0.3f); SetByName(e, t, 0, "Legato", 1f); });+ RenderFinite("note-off trigger", () => { SetByName(e, t, 0, "Mode", 0f); SetByName(e, t, 0, "Trigger", 1f); e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 0.5, 0.9f) }); });+ RenderFinite("modifiers + legato", () => { e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 3.0, 0.9f) }); SetByName(e, t, 0, "Trigger", 0f); SetByName(e, t, 0, "Vel to Len", 0.6f); SetByName(e, t, 0, "Random", 0.3f); SetByName(e, t, 0, "Legato", 1f); });- SetByName(e, t, 0, "Ms", 333f);+ SetByName(e, t, 0, "Ms", 333f); SetByName(e, t, 0, "Division", 6f);int t2 = e.DuplicateTrack(t);- Check(t2 > 0 && Math.Abs(GetByName(e, t2, 0, "Ms") - 333f) < 1e-3, "duplicate track clones Length params");+ Check(t2 > 0 && Math.Abs(GetByName(e, t2, 0, "Ms") - 333f) < 1e-3 && GetByName(e, t2, 0, "Division") == 6f, "duplicate track clones Length params");++ // A project from before Division (11 params): Rate maps onto Division, Key to Len flips sign.+ {+ 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 == 3).MidiEffects[0];+ md.Params = new float[] { 2, 1, 0, 250, 100, 0, 0.4f, 0.5f, 0, 0, 0 }; // Rate 2 = 1/8 dotted, Key to Len +0.5 (old: high longer)+ using var e2 = new NotaEngine();+ ProjectService.Apply(doc, e2, Path.GetTempPath());+ int lt = -1;+ for (int i = 0; e2.TryGetTrackInfo(i, out var ti); i++) if (e2.TrackMidiEffectCount(ti.Id) > 0 && e2.MidiEffectKind(ti.Id, 0) == 3) { lt = ti.Id; break; }+ Check(lt > 0 && GetByName(e2, lt, 0, "Division") == 6f && Math.Abs(GetByName(e2, lt, 0, "Key to Len") + 0.5f) < 1e-4+ && Math.Abs(GetByName(e2, lt, 0, "Vel to Len") - 0.4f) < 1e-4, "legacy Length project: Rate → Division, Key to Len keeps its meaning");+ }++ // 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 == 3).ToList();+ Check(mine.Count >= 25, $"Nota Length 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 Length preset param name exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");+ SetByName(e, t, 0, "View", 1f);+ 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.7f) });+ 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 Length 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");+ }}// ===================== Nota Velocity (MIDI kind 4) rework =====================@@ -6669,7 +6935,9 @@ Console.WriteLine("-- Nota Random --");int m = e.AddMidiEffect(t, 5);Check(m == 0 && e.MidiEffectName(t, 0) == "Nota Random", "add Nota Random");int pc = e.MidiEffectParamCount(t, 0);- Check(pc == 11, $"Nota Random exposes 11 params (got {pc})");+ Check(pc == 13, $"Nota Random exposes 13 params (got {pc})");+ Check(e.MidiEffectParamName(t, 0, 0) == "Chance" && e.MidiEffectParamName(t, 0, 10) == "Seed" && e.MidiEffectParamName(t, 0, 11) == "View"+ && e.MidiEffectParamName(t, 0, 12) == "Lock Bar", "param layout is append-only (… Seed, then View / Lock Bar)");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("Note Range") && pn.Contains("Vel Amt") && pn.Contains("Time Amt") && pn.Contains("Skip")@@ -6718,6 +6986,139 @@ Console.WriteLine("-- Nota Random --");SetByName(e, t, 0, "Note Range", 5f);int t2 = e.DuplicateTrack(t);Check(t2 > 0 && Math.Abs(GetByName(e, t2, 0, "Note Range") - 5f) < 1e-3, "duplicate track clones Random params");++ // Reset to a clean state: every dimension off, per note, Gauss, unlocked.+ void Clean()+ {+ foreach (var n in new[] { "Note Range", "Vel Amt", "Time Amt", "Skip", "Oct Amt", "Dist", "Rate", "Stay In Scale", "Locked", "Lock Bar" }) SetByName(e, t, 0, n, 0f);+ SetByName(e, t, 0, "Chance", 1f); SetByName(e, t, 0, "Seed", 1f);+ }+ var rsc = new float[10];+ int Onset(float[] b) { for (int i = 0; i < b.Length / 2; i++) if (Math.Abs(b[2 * i]) > 1e-4f) return i; return -1; }+ float[] RenderOne(double beat, int frames)+ {+ e.StopTransport();+ e.SetClipNotes(t, 0, new[] { new NotaNote(60, beat, 0.5, 0.9f) });+ var q = new float[2048 * 2]; for (int b = 0; b < 40; b++) e.RenderOffline(q, 2048); // let earlier tails die away+ var buf = new float[frames * 2]; var blk = new float[512 * 2];+ e.Seek(0); e.Play();+ for (int o = 0; o < frames; o += 512) { e.RenderOffline(blk, 512); Array.Copy(blk, 0, buf, o * 2, Math.Min(512, frames - o) * 2); }+ e.StopTransport();+ return buf;+ }++ // Timing: a real delay (up to 100 ms), not clipped to the block — the onset moves by the reported delay.+ Clean();+ int dryOn = Onset(RenderOne(0.25, 16384));+ SetByName(e, t, 0, "Time Amt", 1f); SetByName(e, t, 0, "Dist", 1f);+ float maxDelay = 0; int wetOn = -1; float rep = 0;+ for (int sd = 1; sd <= 8 && maxDelay < 30; sd++)+ {+ SetByName(e, t, 0, "Seed", sd);+ int on = Onset(RenderOne(0.25, 16384));+ e.MidiEffectScope(t, 0, rsc);+ if (rsc[8] > maxDelay) { maxDelay = rsc[8]; wetOn = on; rep = rsc[8]; }+ }+ int wantShift = (int)Math.Round(rep / 1000.0 * 44100);+ Check(maxDelay > 30 && maxDelay <= 100.5f && dryOn >= 0 && Math.Abs(wetOn - dryOn - wantShift) < 64,+ $"Timing delays the note by the reported {rep:0.0} ms (onset {dryOn} → {wetOn}, want +{wantShift})");++ // Lock holds one roll: the same note every bar comes out the same. Unlocked rolls anew per bar.+ int[] BarPitches(bool locked)+ {+ using var be = new NotaEngine();+ be.SetBpm(120); be.SetTimeSignature(4, 4);+ int bt = be.AddInstrumentTrack(); be.AddMidiEffect(bt, 5);+ SetByName(be, bt, 0, "Chance", 1f); SetByName(be, bt, 0, "Note Range", 12f); SetByName(be, bt, 0, "Dist", 1f); SetByName(be, bt, 0, "Seed", 5f);+ SetByName(be, bt, 0, "Locked", locked ? 1f : 0f); SetByName(be, bt, 0, "Lock Bar", 2f);+ be.AddMidiClip(bt, 0.0, 24.0);+ be.SetClipNotes(bt, 0, Enumerable.Range(0, 6).Select(b => new NotaNote(60, b * 4.0 + 1.0, 0.5, 0.9f)).ToArray());+ var ps = new int[6]; var blk = new float[1024 * 2];+ be.Seek(0); be.Play();+ for (int b = 0; b < 6; b++)+ {+ for (int f = 0; f < 88200; f += 1024) be.RenderOffline(blk, 1024); // one bar at 120 BPM+ be.MidiEffectScope(bt, 0, rsc); ps[b] = (int)rsc[5];+ }+ be.StopTransport();+ return ps;+ }+ var lk = BarPitches(true); var ul = BarPitches(false);+ Check(lk.All(x => x == lk[0]) && lk[0] >= 48 && lk[0] <= 72, $"Locked repeats the held roll every bar ({string.Join(" ", lk)})");+ Check(ul.Distinct().Count() > 1, $"unlocked rolls a new value each bar ({string.Join(" ", ul)})");++ // Per bar: one set of values for the whole bar — four notes in a bar move together.+ Clean(); SetByName(e, t, 0, "Note Range", 12f); SetByName(e, t, 0, "Dist", 1f); SetByName(e, t, 0, "Rate", 1f); SetByName(e, t, 0, "Seed", 9f);+ {+ e.StopTransport();+ e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 0.4, 0.9f), new NotaNote(60, 1.0, 0.4, 0.9f), new NotaNote(60, 2.0, 0.4, 0.9f), new NotaNote(60, 3.0, 0.4, 0.9f) });+ var outs = new System.Collections.Generic.List<int>(); var blk = new float[1024 * 2];+ e.Seek(0); e.Play();+ for (int f = 0; f < 88200; f += 1024) { int before = (int)rsc[1]; e.RenderOffline(blk, 1024); e.MidiEffectScope(t, 0, rsc); if ((int)rsc[1] != before) outs.Add((int)rsc[5]); }+ e.StopTransport();+ Check(outs.Count >= 4 && outs.Skip(outs.Count - 4).Distinct().Count() == 1, $"Per bar moves every note of the bar alike ({string.Join(" ", outs)})");+ }++ // Stay in scale: every varied pitch lands in C major.+ Clean(); SetByName(e, t, 0, "Note Range", 12f); SetByName(e, t, 0, "Dist", 1f); SetByName(e, t, 0, "Stay In Scale", 1f);+ {+ var outs = new System.Collections.Generic.HashSet<int>();+ for (int sd = 1; sd <= 12; sd++) { SetByName(e, t, 0, "Seed", sd); RenderOne(0.0, 4096); e.MidiEffectScope(t, 0, rsc); outs.Add((int)rsc[5]); }+ Check(outs.All(p => new[] { 0, 2, 4, 5, 7, 9, 11 }.Contains(((p % 12) + 12) % 12)) && outs.Count > 2, $"Stay in scale keeps notes in C major ({string.Join(" ", outs)})");+ }++ // Skip counts in the telemetry; bypass mid-note releases a transposed note.+ Clean(); SetByName(e, t, 0, "Skip", 1f);+ { int before = (int)(e.MidiEffectScope(t, 0, rsc) >= 4 ? rsc[3] : 0); RenderOne(0.0, 4096); e.MidiEffectScope(t, 0, rsc); Check(rsc[3] > before && rsc[5] == -1, "a skipped note is counted and reported (out −1)"); }+ Clean(); SetByName(e, t, 0, "Note Range", 12f); SetByName(e, t, 0, "Dist", 1f);+ {+ e.StopTransport();+ e.SetClipNotes(t, 0, new[] { new NotaNote(60, 0.0, 0.5, 0.9f) });+ var hb = new float[2048 * 2]; e.Seek(0); e.Play();+ for (int b = 0; b < 4; b++) e.RenderOffline(hb, 2048);+ e.SetMidiEffectBypassed(t, 0, true);+ for (int b = 0; b < 80; b++) e.RenderOffline(hb, 2048);+ e.StopTransport(); e.SetMidiEffectBypassed(t, 0, false);+ Check(Rms(hb, 2048) < 1e-4f, $"bypass mid-note releases the transposed note (tail RMS {Rms(hb, 2048):E1})");+ }++ // MCP: named get / set in musical units.+ {+ var mcp = new Nota.Mcp.Tools.MidiFxTools(e, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());+ mcp.SetRandom(t, 0, chancePercent: 80, noteRangeSemitones: 5, velocityRange: 32, timingMaxMs: 40, skipPercent: 10, octaveRange: 1,+ distribution: "walk", rate: "per-bar", stayInScale: true, seed: 77, locked: true, lockBar: 3, view: "S").GetAwaiter().GetResult();+ var st = mcp.GetRandom(t, 0).GetAwaiter().GetResult();+ Check(st.ChancePercent == 80 && st.NoteRangeSemitones == 5 && st.VelocityRange == 32 && st.TimingMaxMs == 40 && st.SkipPercent == 10+ && st.OctaveRange == 1 && st.Distribution == "walk" && st.Rate == "per-bar" && st.StayInScale && st.Seed == 77 && st.Locked+ && st.LockBar == 3 && st.View == "S", "MCP set_random / get_random round-trip in musical units");+ mcp.SetRandom(t, 0, reroll: true, view: "L").GetAwaiter().GetResult();+ Check(mcp.GetRandom(t, 0).GetAwaiter().GetResult().Seed == 78, "MCP reroll moves to the next seed");+ bool threw = false; try { mcp.SetRandom(t, 0, distribution: "pink").GetAwaiter().GetResult(); } catch (ArgumentException) { threw = true; }+ Check(threw, "MCP set_random rejects an unknown distribution");+ }++ // 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 == 5).ToList();+ Check(mine.Count >= 25, $"Nota Random 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 Random preset param name exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");+ SetByName(e, t, 0, "View", 1f);+ 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.7f), new NotaNote(67, 2.0, 1.0, 0.8f), new NotaNote(72, 3.0, 1.0, 0.9f) });+ 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[88200 * 2]; e.Seek(0); e.Play(); e.RenderOffline(pb, 88200); 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, 88200) < 0.0005f) off.Add(p.DisplayName);+ }+ Check(off.Count == 0, $"every Random 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");+ }}// ===================== Phase 2: more MIDI effects + automation + Map/CC =====