Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
Add macro for Drum Rack and Rhythm
Egor Khindikaynenc1c0d9e84b0c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 05949a98..d1df79e6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,23 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.## [Unreleased]### Added+- **Macros for the Drum Rack and Nota Rhythm, and every kit comes with its own.** The Drum+ Rack has a new **Macro** tab and Rhythm a **MACRO** mode in its centre panel (click MACRO+ next to VOICE). Each shows eight knobs over the whole kit, each with its name and where it+ goes ("→ Reverb · Snare, Clap"); an unassigned knob shows as an empty dashed slot. The Drum+ Rack's right panel lists the selected macro's receivers, with each range as a band whose+ ends you can drag. In Rhythm, right-click a macro to open the same list. **Map** can target+ a pad's own Volume / Pan / Tune / Decay (or a voice's params, or the kit's Swing / Glue),+ the pad instrument's params, and **the built-in effects on the chain**. "All pads" and+ "Every Reverb" map the same target on every pad in one go. The 25 factory kits load with+ macros made for them: **Tune**, **Decay** (the drums that ring; how short it goes depends+ on the kit), **Hats**, **Drive** (**Tape** on the lo-fi kits: the kick's saturation),+ **Room** (the snare and clap reverbs), **Echo** (**Dub** on *Yard*: the hat and percussion+ delays) and **808**/**Sub** on kits with a bass pad. Every range is built around the value+ the kit loads with, so a freshly loaded kit sounds exactly as before. Macros automate,+ MIDI-learn, save with the project and copy with the track. MCP: `get_rhythm_macros`,+ `set_rhythm_macro`, `map_rhythm_macro`, `unmap_rhythm_macro`; `add_macro_mapping` takes+ device -2 for a pad's own controls.- **Nota Rhythm and the Drum Rack share one set of kits.** Rhythm's own synth presets aregone; the 25 factory drum kits now load onto its eight voices too — from the card's kitpicker, from the kits listed under Nota Rhythm in the browser, or by dropping a kit on a@@ -782,6 +799,10 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.returns the compressor's status line.### Fixed+- **Rack macro mappings came loose when a chain's effects changed.** Removing or reordering+ an effect in an Instrument Rack, Drum Rack or Audio Effect Rack chain left the macros+ mapped to whichever device now sat at the old position. A mapping now moves with its+ device, and goes away with it.- **Tempo-synced effects inside a rack ignored the tempo.** A synced Delay, Auto Filter orAuto Pan on a Drum Rack pad, an Instrument Rack chain or an Audio Effect Rack chain ran onits free time; racks now pass the song tempo down to their chains.diff --git a/FEATURES.md b/FEATURES.mdindex b7c806d4..5781568d 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -318,10 +318,13 @@ and user presets, automation, persistence and cloning.contour or sample region, Perform rail with an output meter, a full-width step strip witha velocity lane. Each voice has its own **FX** chain of built-in effects (the voice's FXtab). Its kits are the 25 factory drum kits it shares with the Drum Rack — samples and- per-voice effects — from the card's kit picker or the browser; MCP `get_rhythm`,+ per-voice effects — from the card's kit picker or the browser. Eight **macros** (the+ centre panel's MACRO mode) drive voice params and the voices' effects; each kit loads with+ its own. MCP `get_rhythm`,`set_rhythm_pattern` (text rows), `set_rhythm_voice`, `set_rhythm_perform`,`copy_rhythm_bank`, `audition_rhythm_voice`, `get_rhythm_voice_fx` / `add_rhythm_voice_fx` /- `set_rhythm_voice_fx`, `add_rhythm_kit_track`.+ `set_rhythm_voice_fx`, `add_rhythm_kit_track`, `get_rhythm_macros` / `set_rhythm_macro` /+ `map_rhythm_macro` / `unmap_rhythm_macro`.- **Nota Pentad** — 5-voice analog poly in the Prophet-5 mould: Osc A (saw + pulse, hardsync) and Osc B (saw + triangle + pulse, Lo-Freq, keyboard off), noise, a 24 dB/octresonant filter that self-oscillates and tracks the keyboard, two analog-curve ADSRs,@@ -536,10 +539,12 @@ and user presets, automation, persistence and cloning.- **Nota Instrument Rack** — 8 named macros (mapped with Linear/Exp/Log/S curves), chainswith **key and velocity zones**, gain/meter/M·S, horizontal device cards (GUI / Params),a zone map, rack output (Volume/Glide), Fold/Save.-- **Nota Drum Rack** — 4×4 pads (banks C1–C4, up to 64 pads), Pads, Mixer and Chain views,+- **Nota Drum Rack** — 4×4 pads (banks C1–C4, up to 64 pads), Pads, Mixer, Chain and Macro views,per-pad Volume/Pan/Tune/Decay, named pads (rename, re-choke or remove from a pad'sright-click menu), choke groups (monophonic cut), Swing/Humanize, hot-swap, a pad- oscillogram with a playhead, and each pad's own effect chain. A **kit picker** in the+ oscillogram with a playhead, and each pad's own effect chain. Eight **macros** over the kit+ map onto pad controls (Volume / Pan / Tune / Decay), pad instruments and the pads' effects,+ with draggable ranges per receiver. A **kit picker** in thecard header loads any factory kit in place and names the kit a rack holds. Its clips canbe stepped in the detail panel's **Pattern** tab (see below).- **25 factory kits** under Nota Drum Rack and Nota Rhythm in the browser and in their cards' kit pickers:@@ -553,7 +558,8 @@ and user presets, automation, persistence and cloning.garage), *Mirrorball* (70s disco), *Pit* (orchestral percussion), *Hyper* (hyperpop) and*Crate* (90s boom bap). 16 pads each on the General MIDI map (36–51), hats choked together,with the kit's own swing and humanize, and each pad's own effects (kick saturation, snare and- clap reverb, hat and percussion delay, scaled to the kit). Load onto a new track or drop onto+ clap reverb, hat and percussion delay, scaled to the kit), and the kit's own macros (Tune,+ Decay, Hats, Drive / Tape, Room, Echo, 808 / Sub, as the kit has them). Load onto a new track or drop ontoan existing Drum Rack or Rhythm to replace its pads / voices. The one-shots are synthesized on first launch rather thanshipped as audio (nothing added to the installer) and appear in the Files tab under**Nota Kits**, ready to drag anywhere a sample goes.diff --git a/src/managed/Nota.App/DeviceCards/Instruments/RhythmInstrumentCard.cs b/src/managed/Nota.App/DeviceCards/Instruments/RhythmInstrumentCard.csindex 3a06f2f6..ca49fbe8 100644--- a/src/managed/Nota.App/DeviceCards/Instruments/RhythmInstrumentCard.cs+++ b/src/managed/Nota.App/DeviceCards/Instruments/RhythmInstrumentCard.cs@@ -14,6 +14,11 @@// Reverse, and Start · Length · Tune (st) · Decay · Drive · Level. FX — the// voice's insert chain, the Drum Rack's device slots over RhythmVoiceAccess:// click a slot for the effect's own card, add from the menu or drop one.+// MACRO (the header's VOICE / MACRO) swaps the whole panel for the kit's eight+// macros (MacroPanel): a knob each, its name and where it goes. They map onto+// voice params and onto the voices' effects; a kit loads with its own+// (KitMacros). Map adds a receiver to the selected macro; right-click a macro+// for its receivers and ranges, rename or clear.// PERFORM 186 Swing · Human · Accent (teal — they shape the playing, not the sound),// Master and Glue (the bus compressor), the output meter.// STEP a full-width strip: the selected voice's sixteen steps in bank A–D, a@@ -27,6 +32,7 @@using System;using System.Collections.Generic;+using System.Linq;using Avalonia;using Avalonia.Controls;using Avalonia.Controls.Shapes;@@ -51,6 +57,8 @@ internal sealed class RhythmInstrumentCard : IInstrumentCardprivate const double KitW = 104, RailW = 186, StepH = 46, HeadH = 18, StatusH = 18, GraphW = 112;private static int _voiceTab; // 0 Sound, 1 FX — kept across rebuilds (a voice click, a kit load)+ private static bool _macroMode; // the centre shows the macros instead of the voice+ private static int _macro; // the selected macro, 0..7// A kit voice is named after its one-shot ("04 Clap" → "Clap"); a synth voice by its slot.private static string VoiceLabel(IAudioEngine engine, int track, int v, bool sample)@@ -329,8 +337,24 @@ internal sealed class RhythmInstrumentCard : IInstrumentCardToolTip.SetTip(fileBtn, sampleMode ? $"{sampleName} — click to load another file" : "Load a one-shot into this voice (or drop a file on the voice)");var voiceHead = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Margin = new Thickness(7, 0), VerticalAlignment = VerticalAlignment.Center };- voiceHead.Children.Add(Cap("VOICE"));- voiceHead.Children.Add(new TextBlock { Text = VoiceLabel(engine, track, sel, sampleMode), FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = TextPrimary, VerticalAlignment = VerticalAlignment.Center, MaxWidth = 84, TextTrimming = TextTrimming.CharacterEllipsis });+ // VOICE / MACRO: which the centre shows. The lit one is the one on screen.+ Control ModeCap(string text, bool macro)+ {+ bool on = macro == _macroMode;+ var c = Cap(text, on ? (macro ? AccentBright : NotaPalette.TextStrong) : NotaPalette.TextDisabled);+ var host = new Border { Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Child = c };+ ToolTip.SetTip(host, macro ? "The kit's eight macros — knobs over every voice and its effects" : "The selected voice's sound and effects");+ host.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(host).Properties.IsLeftButtonPressed) return;+ e.Handled = true;+ if (_macroMode != macro) { _macroMode = macro; ctx.RequestRebuild(); }+ };+ return host;+ }+ voiceHead.Children.Add(ModeCap("VOICE", false));+ voiceHead.Children.Add(ModeCap("MACRO", true));+ if (!_macroMode) voiceHead.Children.Add(new TextBlock { Text = VoiceLabel(engine, track, sel, sampleMode), FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = TextPrimary, VerticalAlignment = VerticalAlignment.Center, MaxWidth = 84, TextTrimming = TextTrimming.CharacterEllipsis });int fxCount = engine.RhythmVoiceDeviceCount(track, sel);var tabSeg = Segments(new[] { "Sound", fxCount > 0 ? $"FX {fxCount}" : "FX" }, () => _voiceTab, i =>{@@ -338,16 +362,25 @@ internal sealed class RhythmInstrumentCard : IInstrumentCard_voiceTab = i; ctx.RequestRebuild();}, out _, padX: 6, fontSize: 7);ToolTip.SetTip(tabSeg, "Sound: the voice's source and shape · FX: its own effects, before the kit bus");- voiceHead.Children.Add(tabSeg);+ if (!_macroMode) voiceHead.Children.Add(tabSeg);var voiceTools = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, Margin = new Thickness(0, 0, 6, 0), VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Right };- if (_voiceTab == 0) voiceTools.Children.Add(srcSeg);- if (_voiceTab == 0) voiceTools.Children.Add(fileBtn);- if (_voiceTab == 1)+ var macros = new RhythmMacroSurface(engine, track, idx, isSample, Dots);+ if (_macroMode)+ {+ voiceTools.Children.Add(Mono($"{MacroPanel.Count} slots · {MacroPanel.Assigned(macros)} assigned"));+ Border map = null!;+ map = MacroPanel.Button("Map", teal: true, () => MacroPanel.ShowMapMenu(ctx, macros, map, _macro));+ map.Height = 14;+ ToolTip.SetTip(map, $"Add a receiver to {macros.MacroName(_macro)}: a voice param, a kit setting or a voice's effect");+ voiceTools.Children.Add(map);+ }+ else if (_voiceTab == 0) { voiceTools.Children.Add(srcSeg); voiceTools.Children.Add(fileBtn); }+ else if (_voiceTab == 1){var hint = Mono("signal left → right", NotaPalette.TextDisabled);voiceTools.Children.Add(hint);}- if (sampleMode && _voiceTab == 0)+ if (sampleMode && _voiceTab == 0 && !_macroMode){var revText = new TextBlock { Text = "Reverse", FontSize = 7, FontWeight = FontWeight.SemiBold, VerticalAlignment = VerticalAlignment.Center };var rev = SmallButton(revText, revText,@@ -426,7 +459,9 @@ internal sealed class RhythmInstrumentCard : IInstrumentCardfor (int i = 0; i < cells.Length; i++) { Grid.SetColumn(cells[i], i); knobs.Children.Add(cells[i]); }Control voiceBody;- if (_voiceTab == 1)+ if (_macroMode)+ voiceBody = MacroPanel.Grid(ctx, macros, _macro, m => { _macro = m; ctx.RequestRebuild(); }, readouts, stacked: false, receiversInMenu: true);+ else if (_voiceTab == 1){var fxStrip = new RackCardView(ctx).BuildEffectStrip(new RhythmVoiceAccess(engine, track), sel);voiceBody = new Border { Margin = new Thickness(6, 5), Child = fxStrip };@@ -633,7 +668,7 @@ internal sealed class RhythmInstrumentCard : IInstrumentCard}// ---- status ----------------------------------------------------------------------------- readouts.Add(() => status.Text = RM.Summary(G, pat, sel, sampleMode, sampleName));+ readouts.Add(() => status.Text = _macroMode ? MacroPanel.Status(engine, macros, _macro) : RM.Summary(G, pat, sel, sampleMode, sampleName));var statusBar = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 10 };statusBar.Children.Add(status);Grid.SetColumn(meta, 1); statusBar.Children.Add(meta);@@ -684,6 +719,135 @@ internal sealed class RhythmInstrumentCard : IInstrumentCardreturn root;}+ // ---- the kit macros (MacroPanel), over the Rhythm's own ------------------------------------++ // The macros are the Rhythm's macro1..8 params. A voice is a slot (-1 = the kit itself, for+ // Swing, Glue …); its targets are its own params and its effects' params.+ private sealed class RhythmMacroSurface(IAudioEngine e, int track, Dictionary<string, int> idx, bool[] isSample, string[] dots) : IMacroSurface+ {+ private static readonly string[] VoiceTargets = { "tune", "decay", "punch", "tone", "drive", "level", "pan", "start", "length" };+ private static readonly string[] KitTargets = { "swing", "humanize", "accent", "glue", "volume" };++ public int TrackId => track;+ public int AutomationDevice => -1;+ public int MacroParamIndex(int m) => idx.TryGetValue(RM.MacroId(m), out int i) ? i : -1;+ public string MacroName(int m) => e.RhythmMacroName(track, m);+ public void SetMacroName(int m, string n) => e.RhythmSetMacroName(track, m, n);+ public string SlotNoun => "voices";+ public IReadOnlyList<int> Slots() => new[] { 0, 1, 2, 3, 4, 5, 6, 7 };+ public string SlotName(int v) => v < 0 ? "Kit" : VoiceLabel(e, track, v, isSample[v]);+ public IBrush SlotHue(int v) => v < 0 ? TextTertiary : NotaPalette.Ink(dots[v]);+ public int MappingCount() => e.RhythmMacroMappingCount(track);+ public bool TryGetMapping(int i, out RackMacroMapping m) => e.RhythmTryGetMacroMapping(track, i, out m, out _);+ public int AddMapping(int m, int v, int d, int p, float lo, float hi) => e.RhythmAddMacroMapping(track, m, v, d, p, lo, hi);+ public bool RemoveMapping(int i) => e.RhythmRemoveMacroMapping(track, i);+ public bool SetMappingRange(int i, float lo, float hi) => e.RhythmSetMacroMappingRange(track, i, lo, hi);++ // "v3_decay" → "decay"; a global's id is its own name.+ private string ParamKey(int p) { string id = e.PluginParamId(track, -1, p); int u = id.IndexOf('_'); return u >= 0 ? id[(u + 1)..] : id; }+ private static string Title(string key) => key.Length == 0 ? key : char.ToUpperInvariant(key[0]) + key[1..];+ private bool SampleTune(RackMacroMapping m) => m.DeviceIndex < 0 && m.Chain >= 0 && isSample[m.Chain] && ParamKey(m.ParamIndex) == "tune";++ public (string Param, string Device) TargetLabel(RackMacroMapping m) => m.DeviceIndex < 0+ ? (Title(ParamKey(m.ParamIndex)), "")+ : (e.RhythmVoiceDeviceParamName(track, m.Chain, m.DeviceIndex, m.ParamIndex), e.RhythmVoiceDeviceName(track, m.Chain, m.DeviceIndex));+ public (float Min, float Max) TargetRange(RackMacroMapping m) => m.DeviceIndex < 0+ ? (0f, 1f)+ : (e.RhythmVoiceDeviceParamMin(track, m.Chain, m.DeviceIndex, m.ParamIndex), e.RhythmVoiceDeviceParamMax(track, m.Chain, m.DeviceIndex, m.ParamIndex));+ public float TargetValue(RackMacroMapping m) => m.DeviceIndex < 0+ ? e.PluginParamGet(track, -1, m.ParamIndex)+ : e.RhythmVoiceDeviceParamGet(track, m.Chain, m.DeviceIndex, m.ParamIndex);+ public string FormatTarget(RackMacroMapping m, float x)+ {+ if (m.DeviceIndex >= 0) { var (lo, hi) = TargetRange(m); return MacroPanel.FormatDeviceParam(lo, hi, x); }+ return SampleTune(m) ? Math.Round(RM.SampleSemis(x)).ToString("+0;−0;0", NotaNum.Culture) : $"{Math.Round(x * 100):0}";+ }+ public string TargetUnit(RackMacroMapping m)+ {+ if (m.DeviceIndex >= 0) { var (lo, hi) = TargetRange(m); return MacroPanel.DeviceParamUnit(lo, hi); }+ return SampleTune(m) ? "st" : "%";+ }++ public void FillMapMenu(MenuFlyout menu, int macro, Action changed)+ {+ int P(string id) => idx.TryGetValue(id, out int i) ? i : -1;++ // Every voice at once: the same param, or the same effect on each voice that has it.+ var all = new MenuItem { Header = $"All {RM.Voices} voices" };+ foreach (var key in VoiceTargets)+ {+ var mi = new MenuItem { Header = Title(key) };+ string k = key;+ mi.Click += (_, _) =>+ {+ for (int v = 0; v < RM.Voices; v++) if (P(RM.Id(v, k)) is var p and >= 0) MacroPanel.Map(this, macro, v, -1, p, 0f, 1f);+ changed();+ };+ all.Items.Add(mi);+ }+ var kinds = new List<(int Kind, string Name, int Voice, int Dev)>();+ for (int v = 0; v < RM.Voices; v++)+ for (int d = 0; d < e.RhythmVoiceDeviceCount(track, v); d++)+ {+ int k = e.RhythmVoiceDeviceBuiltinKind(track, v, d);+ if (k >= 0 && kinds.All(x => x.Kind != k)) kinds.Add((k, e.RhythmVoiceDeviceName(track, v, d), v, d));+ }+ if (kinds.Count > 0) all.Items.Add(new Separator());+ foreach (var (kind, dname, v0, d0) in kinds)+ {+ var holders = new List<(int V, int D)>();+ for (int v = 0; v < RM.Voices; v++)+ for (int d = 0; d < e.RhythmVoiceDeviceCount(track, v); d++)+ if (e.RhythmVoiceDeviceBuiltinKind(track, v, d) == kind) { holders.Add((v, d)); break; }+ var fx = new MenuItem { Header = $"Every {dname} ({holders.Count} voice{(holders.Count == 1 ? "" : "s")})" };+ for (int p = 0; p < e.RhythmVoiceDeviceParamCount(track, v0, d0); p++)+ {+ int pp = p;+ var mi = new MenuItem { Header = e.RhythmVoiceDeviceParamName(track, v0, d0, p) };+ mi.Click += (_, _) =>+ {+ foreach (var (v, d) in holders)+ MacroPanel.Map(this, macro, v, d, pp, e.RhythmVoiceDeviceParamMin(track, v, d, pp), e.RhythmVoiceDeviceParamMax(track, v, d, pp));+ changed();+ };+ fx.Items.Add(mi);+ }+ all.Items.Add(fx);+ }+ menu.Items.Add(all);++ var kit = new MenuItem { Header = "Kit" };+ foreach (var key in KitTargets)+ if (P(key) is var p and >= 0)+ kit.Items.Add(MacroPanel.Target(this, Title(key), macro, -1, -1, p, 0f, 1f, changed, MacroPanel.IsMapped(this, macro, -1, -1, p)));+ menu.Items.Add(kit);+ menu.Items.Add(new Separator());++ // One voice: its params, each of its effects.+ for (int v = 0; v < RM.Voices; v++)+ {+ var voice = new MenuItem { Header = SlotName(v) };+ var own = new MenuItem { Header = "Voice" };+ foreach (var key in VoiceTargets)+ if (P(RM.Id(v, key)) is var p and >= 0)+ own.Items.Add(MacroPanel.Target(this, Title(key), macro, v, -1, p, 0f, 1f, changed, MacroPanel.IsMapped(this, macro, v, -1, p)));+ voice.Items.Add(own);+ for (int d = 0; d < e.RhythmVoiceDeviceCount(track, v); d++)+ {+ int dpc = e.RhythmVoiceDeviceParamCount(track, v, d);+ if (dpc <= 0) continue;+ var dev = new MenuItem { Header = e.RhythmVoiceDeviceName(track, v, d) };+ for (int p = 0; p < dpc; p++)+ dev.Items.Add(MacroPanel.Target(this, e.RhythmVoiceDeviceParamName(track, v, d, p), macro, v, d, p,+ e.RhythmVoiceDeviceParamMin(track, v, d, p), e.RhythmVoiceDeviceParamMax(track, v, d, p), changed,+ MacroPanel.IsMapped(this, macro, v, d, p)));+ voice.Items.Add(dev);+ }+ menu.Items.Add(voice);+ }+ }+ }+// A section: card ground, hairline, radius 6, with an 18px header strip.private static Border Section(Control head, Control body){diff --git a/src/managed/Nota.App/DeviceCards/Rack/MacroPanel.cs b/src/managed/Nota.App/DeviceCards/Rack/MacroPanel.csnew file mode 100644index 00000000..9cee13aa--- /dev/null+++ b/src/managed/Nota.App/DeviceCards/Rack/MacroPanel.cs@@ -0,0 +1,501 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Detail · Devices — the kit macros of the Drum Rack and Nota Rhythm, from the almanac's+// "1c Macro" cards. Eight knobs over the whole kit, as a 4 × 2 grid: the value in brass, the+// name, and in teal where it goes ("→ Reverb · Snare, Clap"). An unassigned macro is a dashed,+// empty cell. The selected macro's receivers — every mapping, with its range as a teal band and+// the value it sits at now as a brass tick — are listed by MacroDetail (the Drum Rack's right+// panel); the band's ends drag.+//+// Both instruments reach this through IMacroSurface: the rack's macros (RackCore) and the+// Rhythm's own. A mapping is a RackMacroMapping whose Chain is the pad chain or the voice.+// Map offers every target a slot has — a pad's own controls or a voice's params, the pad+// instrument's params, and each of its effects' params — so a macro can drive the kit's+// built-in effects directly.++using System;+using System.Collections.Generic;+using System.Linq;+using Avalonia;+using Avalonia.Collections;+using Avalonia.Controls;+using Avalonia.Controls.Primitives;+using Avalonia.Controls.Shapes;+using Avalonia.Input;+using Avalonia.Layout;+using Avalonia.Media;+using Nota.Application;+using static Nota.App.DeviceCardKit;++namespace Nota.App;++/// <summary>A kit instrument's macros, as the macro panel sees them.</summary>+internal interface IMacroSurface+{+ int TrackId { get; }+ /// <summary>The plugin-param device index and param index a macro rides (automation, MIDI learn).</summary>+ int AutomationDevice { get; }+ int MacroParamIndex(int macro);+ string MacroName(int macro);+ void SetMacroName(int macro, string name);+ /// <summary>What a slot is called in the plural ("pads", "voices").</summary>+ string SlotNoun { get; }+ /// <summary>The slots a macro can reach (pad chains / voices), in display order.</summary>+ IReadOnlyList<int> Slots();+ string SlotName(int slot);+ IBrush SlotHue(int slot);+ int MappingCount();+ bool TryGetMapping(int index, out RackMacroMapping m);+ int AddMapping(int macro, int slot, int device, int param, float lo, float hi);+ bool RemoveMapping(int index);+ bool SetMappingRange(int index, float lo, float hi);+ /// <summary>The target's short label ("Decay") and the device it sits on ("" for the slot's own).</summary>+ (string Param, string Device) TargetLabel(RackMacroMapping m);+ (float Min, float Max) TargetRange(RackMacroMapping m);+ float TargetValue(RackMacroMapping m);+ /// <summary>A target value as a number in its display unit, and that unit ("%", "st", "dB", "").</summary>+ string FormatTarget(RackMacroMapping m, float v);+ string TargetUnit(RackMacroMapping m);+ /// <summary>Fills the Map menu for <paramref name="macro"/>: every target, grouped by slot.</summary>+ void FillMapMenu(MenuFlyout menu, int macro, Action changed);+}++internal static class MacroPanel+{+ public const int Count = 8;++ /// <summary>The macro's value, 0..1.</summary>+ public static float Value(IAudioEngine e, IMacroSurface s, int m) => e.PluginParamGet(s.TrackId, s.AutomationDevice, s.MacroParamIndex(m));++ public static List<RackMacroMapping> Mappings(IMacroSurface s, int macro, List<int>? indices = null)+ {+ var list = new List<RackMacroMapping>();+ int n = s.MappingCount();+ for (int i = 0; i < n; i++)+ if (s.TryGetMapping(i, out var mm) && mm.Macro == macro) { list.Add(mm); indices?.Add(i); }+ return list;+ }++ public static int Assigned(IMacroSurface s)+ {+ int n = 0;+ for (int m = 0; m < Count; m++) if (Mappings(s, m).Count > 0) n++;+ return n;+ }++ /// <summary>Where a macro goes, in a few words: "→ Decay · 16 pads", "→ Reverb · Snare, Clap".</summary>+ public static string Receivers(IMacroSurface s, int macro, bool compact = false)+ {+ var maps = Mappings(s, macro);+ if (maps.Count == 0) return "";+ var labels = maps.Select(m => { var (p, d) = s.TargetLabel(m); return Short(d.Length > 0 ? d : p); }).Distinct().ToList();+ var slots = maps.Select(m => m.Chain).Distinct().ToList();+ string what = labels.Count <= 2 ? string.Join(" + ", labels) : $"{labels.Count} params";+ string where = slots.Count <= 2+ ? string.Join(", ", slots.Select(s.SlotName))+ : slots.Count == s.Slots().Count ? (compact ? "all" : $"all {slots.Count} {s.SlotNoun}") : $"{slots.Count} {s.SlotNoun}";+ return $"→ {what} · {where}";+ }++ /// <summary>A device name without the maker's prefix ("Nota Reverb" → "Reverb").</summary>+ public static string Short(string name) => name.StartsWith("Nota ", StringComparison.Ordinal) ? name[5..] : name;++ /// <summary>The status line: the selected macro and one other, and the free slots.</summary>+ public static string Status(IAudioEngine e, IMacroSurface s, int sel)+ {+ var parts = new List<string>();+ string One(int m)+ {+ int slots = Mappings(s, m).Select(x => x.Chain).Distinct().Count();+ return $"{s.MacroName(m)} {Pct(Value(e, s, m))} → {slots} {(slots == 1 ? s.SlotNoun.TrimEnd('s') : s.SlotNoun)}";+ }+ if (Mappings(s, sel).Count > 0) parts.Add(One(sel));+ for (int m = 0; m < Count && parts.Count < 2; m++) if (m != sel && Mappings(s, m).Count > 0) parts.Add(One(m));+ int free = Count - Assigned(s);+ parts.Add(free == 0 ? "every macro assigned" : $"{free} free");+ return string.Join(" · ", parts);+ }++ // ==================== the grid ====================++ /// <summary>The eight macros, 4 × 2. <paramref name="stacked"/>: the knob over its words (the+ /// Drum Rack's tall cells); otherwise the knob beside them (Rhythm's). A click selects.</summary>+ public static Control Grid(DeviceCardContext ctx, IMacroSurface s, int selected, Action<int> select, List<Action> tick, bool stacked,+ bool receiversInMenu = false)+ {+ var g = new Grid+ {+ RowDefinitions = new RowDefinitions("*,*"), ColumnDefinitions = new ColumnDefinitions("*,*,*,*"),+ RowSpacing = stacked ? 5 : 4, ColumnSpacing = stacked ? 5 : 4, Margin = stacked ? new Thickness(7, 5) : new Thickness(6, 5),+ };+ for (int m = 0; m < Count; m++)+ {+ var cell = Cell(ctx, s, m, m == selected, select, tick, stacked, receiversInMenu);+ Avalonia.Controls.Grid.SetRow(cell, m / 4); Avalonia.Controls.Grid.SetColumn(cell, m % 4);+ g.Children.Add(cell);+ }+ return g;+ }++ private static Control Cell(DeviceCardContext ctx, IMacroSurface s, int m, bool sel, Action<int> select, List<Action> tick, bool stacked,+ bool receiversInMenu)+ {+ var e = ctx.Engine;+ int track = s.TrackId, di = s.AutomationDevice, pi = s.MacroParamIndex(m);+ bool assigned = Mappings(s, m).Count > 0;+ string pid = RhythmModel.MacroId(m);++ var knob = new Knob(Value(e, s, m), 1.0) { Accent = true, Default = 0.5, Width = Knob.SizeSecondary, Height = Knob.SizeSecondary, IsDim = !assigned };+ var value = new TextBlock { Text = Pct(Value(e, s, m)), FontSize = 7, FontFamily = NotaFonts.MonoFamily, Foreground = assigned ? AccentBright : TextDisabled, LineHeight = 9 };+ knob.ValueChanged += v =>+ {+ e.PluginParamSet(track, di, pi, (float)v);+ value.Text = Pct((float)v);+ ctx.InvokeRackParamRefreshers(); // mapped controls elsewhere on the card follow+ };+ knob.GestureBegin += () => e.BeginAutomationWrite(track, AutomationTarget.PluginParam, di, -1, pid);+ knob.GestureEnd += () =>+ {+ e.EndAutomationWrite(track, AutomationTarget.PluginParam, di, -1, pid);+ if (!sel) select(m); // the macro you turned is the one whose receivers show (after the drag)+ };+ tick.Add(() => { if (!knob.Dragging) { float v = Value(e, s, m); if (Math.Abs(v - knob.Value) > 1e-4) { knob.Value = v; value.Text = Pct(v); } } });+ MidiLearn.Bind(knob, MidiTarget.PluginParam(track, di, pi), $"Macro {m + 1} · {s.MacroName(m)}");++ string name = s.MacroName(m);+ bool custom = name != $"Macro {m + 1}";+ var title = new TextBlock+ {+ Text = assigned || custom ? (stacked ? $"MACRO {m + 1} · {name.ToUpperInvariant()}" : $"{m + 1} · {name.ToUpperInvariant()}") : (stacked ? $"MACRO {m + 1}" : $"{m + 1}"),+ FontSize = 7, FontWeight = FontWeight.Bold, LetterSpacing = 0.56, TextTrimming = TextTrimming.CharacterEllipsis,+ Foreground = !assigned ? TextDisabled : sel ? AccentBright : NotaPalette.TextStrong,+ };+ var recv = new TextBlock+ {+ Text = assigned ? Receivers(s, m, compact: !stacked) : "not assigned", FontSize = 7, TextTrimming = TextTrimming.CharacterEllipsis,+ Foreground = assigned ? NotaPalette.TealBright : TextDisabled,+ };++ Control content;+ if (stacked)+ {+ title.HorizontalAlignment = recv.HorizontalAlignment = value.HorizontalAlignment = HorizontalAlignment.Center;+ var col = new StackPanel { Spacing = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Children = { knob } };+ if (assigned) col.Children.Add(value);+ col.Children.Add(title); col.Children.Add(recv);+ knob.HorizontalAlignment = HorizontalAlignment.Center;+ content = col;+ }+ else+ {+ var words = new StackPanel { Spacing = 1, VerticalAlignment = VerticalAlignment.Center, Children = { title } };+ if (assigned) words.Children.Add(value);+ words.Children.Add(recv);+ var row = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 3, VerticalAlignment = VerticalAlignment.Center };+ row.Children.Add(knob);+ Avalonia.Controls.Grid.SetColumn(words, 1); row.Children.Add(words);+ content = row;+ }++ var cell = new Border+ {+ CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(assigned ? 1 : 0), ClipToBounds = true,+ Padding = stacked ? new Thickness(3) : new Thickness(2, 3, 3, 3), Cursor = new Cursor(StandardCursorType.Hand),+ Background = sel ? NotaPalette.AccentSubtle : assigned ? NotaPalette.SurfaceRaised : NotaPalette.BgSunken,+ BorderBrush = sel ? NotaPalette.BorderBrass : BorderDef, Child = content,+ };+ Control host = cell;+ if (!assigned)+ {+ // An empty macro: a dashed outline instead of the cell edge.+ var dash = new Rectangle+ {+ Stroke = sel ? NotaPalette.BorderBrass : BorderDef, StrokeThickness = 1, StrokeDashArray = new AvaloniaList<double>(3, 2),+ RadiusX = 4, RadiusY = 4, IsHitTestVisible = false,+ };+ host = new Panel { Children = { cell, dash } };+ }+ ToolTip.SetTip(host, assigned+ ? $"{name} — {Receivers(s, m)}\nDrag to turn · click to show its receivers · right-click to map, rename or clear"+ : $"Macro {m + 1} is free — right-click (or Map) to give it a target");+ host.PointerPressed += (_, ev) =>+ {+ var pt = ev.GetCurrentPoint(host).Properties;+ if (pt.IsRightButtonPressed) { ev.Handled = true; ShowMenu(ctx, s, host, m, receiversInMenu); return; }+ if (pt.IsLeftButtonPressed) { ev.Handled = true; if (!sel) select(m); }+ };+ return host;+ }++ // Right-click on a macro: map a target, rename, clear.+ public static void ShowMenu(DeviceCardContext ctx, IMacroSurface s, Control anchor, int m, bool receivers = false)+ {+ var f = new MenuFlyout();+ if (receivers)+ {+ // Where the card has no receivers panel (Rhythm), they open in a flyout.+ var rc = new MenuItem { Header = "Receivers and ranges…" };+ rc.Click += (_, _) => Avalonia.Threading.Dispatcher.UIThread.Post(() => ShowReceivers(ctx, s, anchor, m));+ f.Items.Add(rc);+ }+ var map = new MenuFlyout();+ s.FillMapMenu(map, m, () => { ctx.NotifyChanged(); ctx.RequestRebuild(); });+ var mapItem = new MenuItem { Header = "Map to" };+ foreach (var it in map.Items.ToList()) { map.Items.Remove(it); mapItem.Items.Add(it); }+ f.Items.Add(mapItem);+ var rename = new MenuItem { Header = "Rename…" };+ rename.Click += (_, _) => Avalonia.Threading.Dispatcher.UIThread.Post(() => PromptRename(ctx, s, anchor, m));+ f.Items.Add(rename);+ int n = Mappings(s, m).Count;+ if (n > 0)+ {+ f.Items.Add(new Separator());+ var clear = new MenuItem { Header = $"Clear {n} mapping{(n == 1 ? "" : "s")}" };+ clear.Click += (_, _) => { Clear(s, m); ctx.NotifyChanged(); ctx.RequestRebuild(); };+ f.Items.Add(clear);+ }+ f.ShowAt(anchor, showAtPointer: true);+ }++ public static void Clear(IMacroSurface s, int m)+ {+ for (int i = s.MappingCount() - 1; i >= 0; i--)+ if (s.TryGetMapping(i, out var mm) && mm.Macro == m) s.RemoveMapping(i);+ }++ public static void PromptRename(DeviceCardContext ctx, IMacroSurface s, Control anchor, int m)+ {+ var box = new TextBox { Text = s.MacroName(m), FontSize = 9, Width = 110, Height = 20, Padding = new Thickness(4, 0) };+ var fly = new Flyout { Content = box };+ box.KeyDown += (_, e) =>+ {+ if (e.Key == Key.Enter) { s.SetMacroName(m, (box.Text ?? "").Trim()); ctx.NotifyChanged(); fly.Hide(); ctx.RequestRebuild(); }+ else if (e.Key == Key.Escape) fly.Hide();+ };+ fly.ShowAt(anchor);+ box.SelectAll();+ box.Focus();+ }++ /// <summary>Adds a mapping for <paramref name="macro"/>, replacing one of the same macro on the same target.</summary>+ public static void Map(IMacroSurface s, int macro, int slot, int device, int param, float lo, float hi)+ {+ for (int i = s.MappingCount() - 1; i >= 0; i--)+ if (s.TryGetMapping(i, out var mm) && mm.Macro == macro && mm.Chain == slot && mm.DeviceIndex == device && mm.ParamIndex == param)+ s.RemoveMapping(i);+ s.AddMapping(macro, slot, device, param, lo, hi);+ }++ // ==================== the selected macro's receivers ====================++ /// <summary>The selected macro: its name and value, every receiver with its range (drag the+ /// band's ends), and Map / Rename / Clear.</summary>+ public static Control Detail(DeviceCardContext ctx, IMacroSurface s, int m, List<Action> tick)+ {+ var e = ctx.Engine;+ var val = new TextBlock { FontSize = 7, FontFamily = NotaFonts.MonoFamily, Foreground = AccentBright, VerticalAlignment = VerticalAlignment.Center };+ tick.Add(() => val.Text = Pct(Value(e, s, m)));+ var head = new Grid { Height = 20, ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 5, Margin = new Thickness(8, 0) };+ head.Children.Add(Cap($"MACRO {m + 1}"));+ var nm = new TextBlock { Text = s.MacroName(m), FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = TextPrimary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };+ Avalonia.Controls.Grid.SetColumn(nm, 1); head.Children.Add(nm);+ Avalonia.Controls.Grid.SetColumn(val, 2); head.Children.Add(val);+ var headBar = new Border { BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Child = head };++ var idx = new List<int>();+ var maps = Mappings(s, m, idx);+ // By slot, then target, so a pad's receivers sit together.+ var order = Enumerable.Range(0, maps.Count).OrderBy(k => maps[k].Chain).ThenBy(k => maps[k].DeviceIndex).ThenBy(k => maps[k].ParamIndex).ToList();+ maps = order.Select(k => maps[k]).ToList();+ idx = order.Select(k => idx[k]).ToList();+ var rows = new StackPanel { Spacing = 6 };+ var capRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };+ capRow.Children.Add(Cap("RECEIVERS"));+ var mm2 = new TextBlock { Text = "min → max", FontSize = 7, FontFamily = NotaFonts.MonoFamily, Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center };+ Avalonia.Controls.Grid.SetColumn(mm2, 1); capRow.Children.Add(mm2);+ rows.Children.Add(capRow);+ // One receiver per row. When a macro drives several params on each slot, the rows say which.+ bool manyParams = maps.Select(x => s.TargetLabel(x)).Distinct().Count() > 1;+ for (int k = 0; k < maps.Count; k++) rows.Children.Add(ReceiverRow(ctx, s, idx[k], maps[k], manyParams, tick));+ if (maps.Count == 0)+ rows.Children.Add(new TextBlock+ {+ Text = "Nothing mapped yet. Map gives this knob a pad control, an instrument param or any of the kit's effects.",+ FontSize = 8, Foreground = TextTertiary, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, 4, 0, 0),+ });+ var scroll = new ScrollViewer { Content = rows, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled };++ Border mapBtn = null!;+ mapBtn = Button("Map", teal: true, () => ShowMapMenu(ctx, s, mapBtn, m));+ ToolTip.SetTip(mapBtn, "Add a receiver: a pad control, the pad's instrument or one of its effects");+ Border renameBtn = null!;+ renameBtn = Button("Rename", teal: false, () => PromptRename(ctx, s, renameBtn, m));+ var clearBtn = Button("Clear", teal: false, () => { Clear(s, m); ctx.NotifyChanged(); ctx.RequestRebuild(); });+ ToolTip.SetTip(clearBtn, "Remove every receiver of this macro");+ var buttons = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*"), ColumnSpacing = 4 };+ buttons.Children.Add(mapBtn);+ Avalonia.Controls.Grid.SetColumn(renameBtn, 1); buttons.Children.Add(renameBtn);+ Avalonia.Controls.Grid.SetColumn(clearBtn, 2); buttons.Children.Add(clearBtn);+ var foot = new Border+ {+ BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 5, 0, 0), Child = buttons,+ };++ DockPanel.SetDock(foot, Dock.Bottom);+ var body = new DockPanel { LastChildFill = true, Margin = new Thickness(8, 6), Children = { foot, scroll } };+ DockPanel.SetDock(headBar, Dock.Top);+ return new DockPanel { LastChildFill = true, Children = { headBar, body } };+ }++ /// <summary>The selected macro's receivers panel in a flyout (Rhythm has no panel for it).</summary>+ public static void ShowReceivers(DeviceCardContext ctx, IMacroSurface s, Control anchor, int m)+ {+ var tick = new List<Action>();+ var box = new Border+ {+ Width = 240, Height = 190, Background = NotaPalette.SurfaceCard, BorderBrush = BorderDef, BorderThickness = new Thickness(1),+ CornerRadius = NotaRadius.Tile, ClipToBounds = true, Child = Detail(ctx, s, m, tick),+ };+ var timer = new Avalonia.Threading.DispatcherTimer { Interval = TimeSpan.FromMilliseconds(50) };+ timer.Tick += (_, _) => { foreach (var t in tick) t(); };+ var fly = new Flyout { Content = box, Placement = PlacementMode.BottomEdgeAlignedLeft };+ fly.Opened += (_, _) => timer.Start();+ fly.Closed += (_, _) => timer.Stop();+ fly.ShowAt(anchor);+ }++ /// <summary>The Map menu on its own (the Map buttons).</summary>+ public static void ShowMapMenu(DeviceCardContext ctx, IMacroSurface s, Control anchor, int m)+ {+ var f = new MenuFlyout();+ s.FillMapMenu(f, m, () => { ctx.NotifyChanged(); ctx.RequestRebuild(); });+ f.ShowAt(anchor);+ }++ private static Control ReceiverRow(DeviceCardContext ctx, IMacroSurface s, int index, RackMacroMapping mm, bool withParam, List<Action> tick)+ {+ var (pn, dev) = s.TargetLabel(mm);+ var (min, max) = s.TargetRange(mm);+ double span = Math.Max(1e-6, max - min);+ double fLo = Math.Clamp((mm.RangeMin - min) / span, 0, 1), fHi = Math.Clamp((mm.RangeMax - min) / span, 0, 1);++ var hue = new Border { Width = 3, Height = 8, CornerRadius = NotaRadius.Bar, Background = s.SlotHue(mm.Chain), VerticalAlignment = VerticalAlignment.Center };+ string label = withParam ? $"{s.SlotName(mm.Chain)} · {pn}" : s.SlotName(mm.Chain);+ var name = new TextBlock { Text = label, FontSize = 8, FontWeight = FontWeight.Medium, Foreground = TextPrimary, Width = withParam ? 74 : 50, TextTrimming = TextTrimming.CharacterEllipsis, VerticalAlignment = VerticalAlignment.Center };+ ToolTip.SetTip(name, dev.Length > 0 ? $"{s.SlotName(mm.Chain)} · {Short(dev)} · {pn}" : $"{s.SlotName(mm.Chain)} · {pn}");++ var band = new Border { Height = 3, CornerRadius = NotaRadius.Bar, Background = NotaPalette.Teal, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center };+ var now = new Border { Width = 2, Height = 7, Background = AccentBright, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center };+ var track = new Panel+ {+ Height = 9, Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.SizeWestEast), VerticalAlignment = VerticalAlignment.Center,+ Children = { new Border { Height = 3, CornerRadius = NotaRadius.Bar, Background = NotaPalette.BgSunken, VerticalAlignment = VerticalAlignment.Center }, band, now },+ };+ var vals = new TextBlock { FontSize = 7, FontFamily = NotaFonts.MonoFamily, Foreground = TextSecondary, Width = 46, TextAlignment = TextAlignment.Right, VerticalAlignment = VerticalAlignment.Center };+ string unit = s.TargetUnit(mm);+ void Text() => vals.Text = $"{s.FormatTarget(mm, (float)(min + fLo * span))}–{s.FormatTarget(mm, (float)(min + fHi * span))}"+ + (unit.Length > 0 ? "\u2009" + unit : "");+ void Layout()+ {+ double w = track.Bounds.Width;+ double a = Math.Min(fLo, fHi), b = Math.Max(fLo, fHi); // an inverted range still draws+ band.Margin = new Thickness(a * w, 0, 0, 0); band.Width = Math.Max(2, (b - a) * w);+ double cur = Math.Clamp((s.TargetValue(mm) - min) / span, 0, 1);+ now.Margin = new Thickness(Math.Clamp(cur * w - 1, 0, Math.Max(0, w - 2)), 0, 0, 0);+ }+ Text();+ tick.Add(Layout);+ track.SizeChanged += (_, _) => Layout();++ int drag = 0; // 1 = the low end, 2 = the high end+ void Apply(double x)+ {+ double f = Math.Clamp(x / Math.Max(1, track.Bounds.Width), 0, 1);+ if (drag == 1) fLo = f; else fHi = f;+ s.SetMappingRange(index, (float)(min + fLo * span), (float)(min + fHi * span));+ Text(); Layout();+ }+ track.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(track).Properties.IsLeftButtonPressed) return;+ double x = e.GetPosition(track).X, w = track.Bounds.Width;+ drag = Math.Abs(x - fLo * w) <= Math.Abs(x - fHi * w) ? 1 : 2;+ e.Pointer.Capture(track); e.Handled = true; Apply(x);+ };+ track.PointerMoved += (_, e) => { if (drag != 0) Apply(e.GetPosition(track).X); };+ track.PointerReleased += (_, e) => { if (drag != 0) { drag = 0; e.Pointer.Capture(null); ctx.NotifyChanged(); } };+ ToolTip.SetTip(track, "The range the macro sweeps: drag either end · the brass tick is where it is now");++ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*,Auto"), ColumnSpacing = 5 };+ g.Children.Add(hue);+ Avalonia.Controls.Grid.SetColumn(name, 1); g.Children.Add(name);+ Avalonia.Controls.Grid.SetColumn(track, 2); g.Children.Add(track);+ Avalonia.Controls.Grid.SetColumn(vals, 3); g.Children.Add(vals);+ g.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(g).Properties.IsRightButtonPressed) return;+ e.Handled = true;+ var f = new MenuFlyout();+ var rm = new MenuItem { Header = "Remove this receiver" };+ rm.Click += (_, _) => { s.RemoveMapping(index); ctx.NotifyChanged(); ctx.RequestRebuild(); };+ f.Items.Add(rm);+ f.ShowAt(g, showAtPointer: true);+ };+ return g;+ }++ // ---- small builders ------------------------------------------------------------------++ public static TextBlock Cap(string t) => new()+ {+ Text = t, FontSize = NotaType.KnobLabel, FontWeight = FontWeight.Bold, LetterSpacing = NotaType.KnobLabelTracking,+ Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center,+ };++ /// <summary>A 16px action button; the teal one is Map (it adds modulation).</summary>+ public static Border Button(string text, bool teal, Action click)+ {+ var tb = new TextBlock+ {+ Text = text, FontSize = 7, FontWeight = FontWeight.SemiBold, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center,+ Foreground = teal ? NotaPalette.TealBright : NotaPalette.TextStrong,+ };+ IBrush rest = teal ? NotaPalette.Wash(NotaPalette.Teal, 0x33) : NotaPalette.SurfaceRaised;+ var b = new Border+ {+ Height = 16, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), Padding = new Thickness(6, 0),+ Background = rest, BorderBrush = teal ? NotaPalette.Teal : BorderDef, Cursor = new Cursor(StandardCursorType.Hand), Child = tb,+ };+ b.PointerEntered += (_, _) => b.Background = teal ? NotaPalette.Wash(NotaPalette.Teal, 0x55) : NotaPalette.SurfaceHover;+ b.PointerExited += (_, _) => b.Background = rest;+ b.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return;+ e.Handled = true; click();+ };+ return b;+ }++ /// <summary>A menu item that maps <paramref name="macro"/> to one target.</summary>+ public static MenuItem Target(IMacroSurface s, string header, int macro, int slot, int device, int param, float lo, float hi, Action changed, bool mapped = false)+ {+ var mi = new MenuItem { Header = header };+ if (mapped) mi.Icon = new Ellipse { Width = 6, Height = 6, Fill = NotaPalette.Teal };+ mi.Click += (_, _) => { Map(s, macro, slot, device, param, lo, hi); changed(); };+ return mi;+ }++ /// <summary>A device param as the receivers show it: 0..1 params in percent, the rest as numbers.</summary>+ public static string FormatDeviceParam(float min, float max, float v)+ => min == 0f && max == 1f ? $"{Math.Round(v * 100):0}" : v.ToString(Math.Abs(max - min) >= 20 ? "0" : "0.##", NotaNum.Culture);+ public static string DeviceParamUnit(float min, float max) => min == 0f && max == 1f ? "%" : "";++ public static bool IsMapped(IMacroSurface s, int macro, int slot, int device, int param)+ {+ int n = s.MappingCount();+ for (int i = 0; i < n; i++)+ if (s.TryGetMapping(i, out var mm) && mm.Macro == macro && mm.Chain == slot && mm.DeviceIndex == device && mm.ParamIndex == param) return true;+ return false;+ }+}diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.Drum.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.Drum.csindex 043e0d36..fd933205 100644--- a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.Drum.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.Drum.cs@@ -13,8 +13,12 @@// there (several fill the pads after it). Fold hides the empty pads.// Mixer — the bank's loaded pads as rows: volume, pan, mute · solo · choke.// Chain — the selected pad's device chain: its instrument and insert effects.+// Macro — the kit's eight macros (MacroPanel): a knob each, the name, and where+// it goes; a kit loads with its own (KitMacros), mapped onto the pads'+// controls and their effects.// Pad 186 the selected pad: its one-shot, volume · pan · tune · decay, the choke-// group, and its instrument's editor.+// group, and its instrument's editor. In Macro, the selected macro instead: its+// receivers with their ranges, and Map · Rename · Clear.// Status the selection and the kit, in words.//// A pad's colour is its track-palette slot; brass means selection only, and a pad that is@@ -36,11 +40,12 @@ namespace Nota.App;internal sealed partial class RackCardView{- private static int _drumView; // 0 Pads, 1 Mixer, 2 Chain+ private static int _drumView; // 0 Pads, 1 Mixer, 2 Chain, 3 Macro+ private static int _drumMacro; // Macro: the selected macro, 0..7private static int _drumBank; // 0..3 → C1..C4 (notes 36 + bank × 16)private static bool _drumFold; // Pads: hide the empty pads- private static readonly string[] DrumViews = { "Pads", "Mixer", "Chain" };+ private static readonly string[] DrumViews = { "Pads", "Mixer", "Chain", "Macro" };private static readonly string[] BankNames = { "C1", "C2", "C3", "C4" };private static readonly string[] ChokeNames = { "Off", "1", "2", "3", "4" };private const double DrumPadW = 186, DrumTabH = 20, DrumStripH = 22, DrumStatusH = 18, MixRowH = 13;@@ -64,13 +69,17 @@ internal sealed partial class RackCardViewvar readout = DrumMono("", TextTertiary, NotaType.Axis);readout.Margin = new Thickness(0, 0, 8, 0);readout.HorizontalAlignment = HorizontalAlignment.Right;+ var macros = new DrumMacroSurface(this, a);Control view = _drumView switch{1 => DrumMixer(a, readout),2 => DrumChain(a),+ 3 => MacroPanel.Grid(_ctx, macros, _drumMacro, m => { _drumMacro = m; DeferRebuild(); }, _irTick, stacked: true),_ => DrumGrid(a),};- if (_drumView != 1)+ if (_drumView == 3)+ readout.Text = $"{MacroPanel.Count} slots · {MacroPanel.Assigned(macros)} assigned";+ else if (_drumView != 1){int inBank = pads.Count(c => InBank(a.ChainTriggerNote(c)));readout.Text = $"{BankNames[_drumBank]} · {inBank}/16 loaded";@@ -82,7 +91,7 @@ internal sealed partial class RackCardViewGrid.SetRow(strip, 1); left.Children.Add(strip);Grid.SetRow(view, 2); left.Children.Add(view);- var panel = DrumBox(DrumPadPanel(a));+ var panel = DrumBox(_drumView == 3 ? MacroPanel.Detail(_ctx, macros, _drumMacro, _irTick) : DrumPadPanel(a));panel.Width = DrumPadW;var body = new Grid@@ -93,7 +102,7 @@ internal sealed partial class RackCardViewbody.Children.Add(DrumBox(left));Grid.SetColumn(panel, 1); body.Children.Add(panel);- var statusHost = DrumStatus(a, pads);+ var statusHost = DrumStatus(a, pads, macros);DockPanel.SetDock(statusHost, Dock.Bottom);var root = new DockPanel { LastChildFill = true, Background = NotaPalette.Gutter, Children = { statusHost, body } };@@ -643,7 +652,7 @@ internal sealed partial class RackCardView// ---- status strip (18) ------------------------------------------------------------ private Control DrumStatus(IRackAccess a, List<int> pads)+ private Control DrumStatus(IRackAccess a, List<int> pads, IMacroSurface macros){var status = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };var meta = DrumMono("", TextSecondary, 8);@@ -663,6 +672,7 @@ internal sealed partial class RackCardViewstring Summary(){string bank = $"Bank {BankNames[_drumBank]}";+ if (_drumView == 3) return MacroPanel.Status(E, macros, _drumMacro);if (_drumView == 1){var inBank = pads.Where(c => InBank(a.ChainTriggerNote(c))).ToList();@@ -904,4 +914,169 @@ internal sealed partial class RackCardView};return b;}++ // ---- the kit macros (MacroPanel), over the rack's macros ------------------------------++ // The rack's eight macros ride its plugin params (index = macro). A pad is a slot; its+ // targets are its own controls (volume · pan · tune · decay), its instrument's params and+ // its effects' params.+ private sealed class DrumMacroSurface(RackCardView v, IRackAccess a) : IMacroSurface+ {+ private IAudioEngine E => v.E;+ public int TrackId => v.T;+ public int AutomationDevice => a.AutomationDeviceIndex;+ public int MacroParamIndex(int m) => m;+ public string MacroName(int m) => a.MacroName(m);+ public void SetMacroName(int m, string n) => a.SetMacroName(m, n);+ public string SlotNoun => "pads";+ public IReadOnlyList<int> Slots() => LoadedPads(a);+ public string SlotName(int c) => v.PadName(a, c);+ public IBrush SlotHue(int c) => PadHue(c);+ public int MappingCount() => a.MappingCount();+ public bool TryGetMapping(int i, out RackMacroMapping m) => a.TryGetMapping(i, out m);+ public int AddMapping(int m, int c, int d, int p, float lo, float hi) => a.AddMacroMapping(m, c, d, p, lo, hi);+ public bool RemoveMapping(int i) => a.RemoveMapping(i);+ public bool SetMappingRange(int i, float lo, float hi) => a.SetMappingRange(i, lo, hi);++ public (string Param, string Device) TargetLabel(RackMacroMapping m) => m.DeviceIndex switch+ {+ RackMacroMapping.PadControls => (PadParam(m.ParamIndex), ""),+ < 0 => (a.ChainInstrumentParamName(m.Chain, m.ParamIndex), InstrumentWord(a, m.Chain)),+ _ => (a.ChainDeviceParamName(m.Chain, m.DeviceIndex, m.ParamIndex), a.ChainDeviceName(m.Chain, m.DeviceIndex)),+ };+ public (float Min, float Max) TargetRange(RackMacroMapping m) => m.DeviceIndex switch+ {+ // Tune's ±48 st would squeeze a musical range into a sliver: the bar shows ±24.+ RackMacroMapping.PadControls => m.ParamIndex == RackMacroMapping.PadTune ? (-24f, 24f) : PadRange(m.ParamIndex),+ < 0 => (0f, 1f),+ _ => (a.ChainDeviceParamMin(m.Chain, m.DeviceIndex, m.ParamIndex), a.ChainDeviceParamMax(m.Chain, m.DeviceIndex, m.ParamIndex)),+ };+ public float TargetValue(RackMacroMapping m) => m.DeviceIndex switch+ {+ RackMacroMapping.PadControls => m.ParamIndex switch+ {+ RackMacroMapping.PadVolume => a.ChainGain(m.Chain),+ RackMacroMapping.PadPan => a.ChainPan(m.Chain),+ RackMacroMapping.PadTune => E.RackChainTune(TrackId, m.Chain),+ _ => E.RackChainDecay(TrackId, m.Chain),+ },+ < 0 => a.ChainInstrumentParamGet(m.Chain, m.ParamIndex),+ _ => a.ChainDeviceParamGet(m.Chain, m.DeviceIndex, m.ParamIndex),+ };+ public string FormatTarget(RackMacroMapping m, float x)+ {+ if (m.DeviceIndex >= 0) { var (lo, hi) = TargetRange(m); return MacroPanel.FormatDeviceParam(lo, hi, x); }+ if (m.DeviceIndex != RackMacroMapping.PadControls) return $"{Math.Round(x * 100):0}";+ return m.ParamIndex switch+ {+ RackMacroMapping.PadVolume => x <= 0.001f ? "−∞" : (20 * Math.Log10(x)).ToString("+0;−0;0", NotaNum.Culture),+ RackMacroMapping.PadPan => PanText(x),+ RackMacroMapping.PadTune => Math.Round(x).ToString("+0;−0;0", NotaNum.Culture),+ _ => $"{Math.Round(x * 100):0}",+ };+ }+ public string TargetUnit(RackMacroMapping m)+ {+ if (m.DeviceIndex >= 0) { var (lo, hi) = TargetRange(m); return MacroPanel.DeviceParamUnit(lo, hi); }+ if (m.DeviceIndex != RackMacroMapping.PadControls) return "%";+ return m.ParamIndex switch { RackMacroMapping.PadVolume => "dB", RackMacroMapping.PadPan => "", RackMacroMapping.PadTune => "st", _ => "%" };+ }++ private static string PadParam(int p) => p >= 0 && p < RackMacroMapping.PadParamNames.Length ? RackMacroMapping.PadParamNames[p] : "?";+ private static (float, float) PadRange(int p) => p >= 0 && p < 4 ? (RackMacroMapping.PadParamMin[p], RackMacroMapping.PadParamMax[p]) : (0f, 1f);+ // What a new pad-control mapping sweeps: a musical span rather than the whole control.+ private static (float, float) PadDefault(int p) => p switch+ {+ RackMacroMapping.PadVolume => (0f, 1f),+ RackMacroMapping.PadPan => (-1f, 1f),+ RackMacroMapping.PadTune => (-12f, 12f),+ _ => (0f, 1f),+ };++ public void FillMapMenu(MenuFlyout menu, int macro, Action changed)+ {+ var pads = LoadedPads(a);+ if (pads.Count == 0) { menu.Items.Add(new MenuItem { Header = "No pads to map", IsEnabled = false }); return; }++ // Every pad at once: its own controls, or the same effect on each pad that has it.+ var all = new MenuItem { Header = $"All {pads.Count} pads" };+ for (int p = 0; p < 4; p++)+ {+ int pp = p;+ var (lo, hi) = PadDefault(p);+ var mi = new MenuItem { Header = PadParam(p) };+ mi.Click += (_, _) => { foreach (int c in pads) MacroPanel.Map(this, macro, c, RackMacroMapping.PadControls, pp, lo, hi); changed(); };+ all.Items.Add(mi);+ }+ var kinds = new List<(int Kind, string Name, int Chain, int Dev)>();+ foreach (int c in pads)+ for (int d = 0; d < a.ChainDeviceCount(c); d++)+ {+ int k = a.ChainDeviceBuiltinKind(c, d);+ if (k >= 0 && kinds.All(x => x.Kind != k)) kinds.Add((k, a.ChainDeviceName(c, d), c, d));+ }+ if (kinds.Count > 0) all.Items.Add(new Separator());+ foreach (var (kind, dname, c0, d0) in kinds)+ {+ // The pads holding this effect; each maps its first one.+ var holders = pads.Select(c => (c, d: FirstOfKind(c, kind))).Where(x => x.d >= 0).ToList();+ var fx = new MenuItem { Header = $"Every {dname} ({holders.Count} pad{(holders.Count == 1 ? "" : "s")})" };+ for (int p = 0; p < a.ChainDeviceParamCount(c0, d0); p++)+ {+ int pp = p;+ var mi = new MenuItem { Header = a.ChainDeviceParamName(c0, d0, p) };+ mi.Click += (_, _) =>+ {+ foreach (var (c, d) in holders)+ MacroPanel.Map(this, macro, c, d, pp, a.ChainDeviceParamMin(c, d, pp), a.ChainDeviceParamMax(c, d, pp));+ changed();+ };+ fx.Items.Add(mi);+ }+ all.Items.Add(fx);+ }+ menu.Items.Add(all);+ menu.Items.Add(new Separator());++ // One pad: its controls, its instrument, each of its effects.+ foreach (int c in pads)+ {+ var pad = new MenuItem { Header = $"{v.PadName(a, c)} · {NoteName(a.ChainTriggerNote(c))}" };+ var ctl = new MenuItem { Header = "Pad" };+ for (int p = 0; p < 4; p++)+ {+ var (lo, hi) = PadDefault(p);+ ctl.Items.Add(MacroPanel.Target(this, PadParam(p), macro, c, RackMacroMapping.PadControls, p, lo, hi, changed,+ MacroPanel.IsMapped(this, macro, c, RackMacroMapping.PadControls, p)));+ }+ pad.Items.Add(ctl);+ int ipc = a.ChainInstrumentParamCount(c);+ if (ipc > 0)+ {+ var inst = new MenuItem { Header = InstrumentWord(a, c) };+ for (int p = 0; p < ipc; p++)+ inst.Items.Add(MacroPanel.Target(this, a.ChainInstrumentParamName(c, p), macro, c, -1, p, 0f, 1f, changed,+ MacroPanel.IsMapped(this, macro, c, -1, p)));+ pad.Items.Add(inst);+ }+ for (int d = 0; d < a.ChainDeviceCount(c); d++)+ {+ int dpc = a.ChainDeviceParamCount(c, d);+ if (dpc <= 0) continue;+ var dev = new MenuItem { Header = a.ChainDeviceName(c, d) };+ for (int p = 0; p < dpc; p++)+ dev.Items.Add(MacroPanel.Target(this, a.ChainDeviceParamName(c, d, p), macro, c, d, p,+ a.ChainDeviceParamMin(c, d, p), a.ChainDeviceParamMax(c, d, p), changed, MacroPanel.IsMapped(this, macro, c, d, p)));+ pad.Items.Add(dev);+ }+ menu.Items.Add(pad);+ }+ }++ private int FirstOfKind(int c, int kind)+ {+ for (int d = 0; d < a.ChainDeviceCount(c); d++) if (a.ChainDeviceBuiltinKind(c, d) == kind) return d;+ return -1;+ }+ }}diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.csindex a1714f42..89d57fd2 100644--- a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs@@ -615,10 +615,12 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)private Control IrMappingRow(IRackAccess a, int mappingIndex, RackMacroMapping mm){- string dev = mm.DeviceIndex < 0 ? a.ChainInstrumentName(mm.Chain) : a.ChainDeviceName(mm.Chain, mm.DeviceIndex);- string pn = mm.DeviceIndex < 0 ? a.ChainInstrumentParamName(mm.Chain, mm.ParamIndex) : a.ChainDeviceParamName(mm.Chain, mm.DeviceIndex, mm.ParamIndex);+ bool pad = mm.DeviceIndex == RackMacroMapping.PadControls && mm.ParamIndex is >= 0 and < 4;+ string dev = pad ? $"Chain {mm.Chain + 1}" : mm.DeviceIndex < 0 ? a.ChainInstrumentName(mm.Chain) : a.ChainDeviceName(mm.Chain, mm.DeviceIndex);+ string pn = pad ? RackMacroMapping.PadParamNames[mm.ParamIndex] : mm.DeviceIndex < 0 ? a.ChainInstrumentParamName(mm.Chain, mm.ParamIndex) : a.ChainDeviceParamName(mm.Chain, mm.DeviceIndex, mm.ParamIndex);float pMin = 0, pMax = 1;- if (mm.DeviceIndex >= 0) { pMin = a.ChainDeviceParamMin(mm.Chain, mm.DeviceIndex, mm.ParamIndex); pMax = a.ChainDeviceParamMax(mm.Chain, mm.DeviceIndex, mm.ParamIndex); }+ if (pad) { pMin = RackMacroMapping.PadParamMin[mm.ParamIndex]; pMax = RackMacroMapping.PadParamMax[mm.ParamIndex]; }+ else if (mm.DeviceIndex >= 0) { pMin = a.ChainDeviceParamMin(mm.Chain, mm.DeviceIndex, mm.ParamIndex); pMax = a.ChainDeviceParamMax(mm.Chain, mm.DeviceIndex, mm.ParamIndex); }double span = Math.Max(1e-6, pMax - pMin);double fLo = Math.Clamp((mm.RangeMin - pMin) / span, 0, 1), fHi = Math.Clamp((mm.RangeMax - pMin) / span, 0, 1);var name = new TextBlock { Text = $"{dev} · {pn}", FontSize = 9, Foreground = IrTxt, Width = 122, TextTrimming = TextTrimming.CharacterEllipsis, VerticalAlignment = VerticalAlignment.Center };@@ -1271,7 +1273,9 @@ internal sealed partial class RackCardView(DeviceCardContext ctx){ count++; lastChain = mm.Chain; lastDev = mm.DeviceIndex; lastParam = mm.ParamIndex; }if (count == 1){- string pn = lastDev < 0+ string pn = lastDev == RackMacroMapping.PadControls && lastParam is >= 0 and < 4+ ? RackMacroMapping.PadParamNames[lastParam]+ : lastDev < 0? a.ChainInstrumentParamName(lastChain, lastParam): a.ChainDeviceParamName(lastChain, lastDev, lastParam);text = $"→ C{lastChain + 1} {pn}";diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.csindex f5fb18e6..fd289ba2 100644--- a/src/managed/Nota.Application/Engine/EngineContracts.cs+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs@@ -181,7 +181,18 @@ public enum GamepadAxis/// <summary>An Instrument Rack macro mapping: macro <paramref name="Macro"/> drives the target/// param over [<paramref name="RangeMin"/>, <paramref name="RangeMax"/>] in the target's own units.-/// <paramref name="DeviceIndex"/> < 0 targets the chain's instrument (plugin-param index);-/// otherwise the device at that chain position (generic-param index).</summary>+/// <paramref name="DeviceIndex"/> -1 targets the chain's instrument (plugin-param index), -2+/// (<see cref="PadControls"/>) the chain's own strip — a Drum Rack pad's Volume / Pan / Tune /+/// Decay; otherwise the device at that chain position (generic-param index).</summary>public readonly record struct RackMacroMapping(- int Macro, int Chain, int DeviceIndex, int ParamIndex, float RangeMin, float RangeMax);+ int Macro, int Chain, int DeviceIndex, int ParamIndex, float RangeMin, float RangeMax)+{+ /// <summary>DeviceIndex of a mapping onto the chain's own controls (RackCore::kPadControls).</summary>+ public const int PadControls = -2;+ /// <summary>The pad controls a mapping can drive, by ParamIndex, with their ranges (gain is linear,+ /// pan −1..1, tune in semitones, decay 0..1 with 1 = hold).</summary>+ public static readonly string[] PadParamNames = { "Volume", "Pan", "Tune", "Decay" };+ public static readonly float[] PadParamMin = { 0f, -1f, -48f, 0f };+ public static readonly float[] PadParamMax = { 2f, 1f, 48f, 1f };+ public const int PadVolume = 0, PadPan = 1, PadTune = 2, PadDecay = 3;+}diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex e0c0df08..c5c9b0a1 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -300,6 +300,20 @@ public interface IAudioEngine : IDisposable/// <summary>The factory kit a Rhythm's voices were loaded from ("" = none) — display only, saved with the track.</summary>string RhythmKitName(int trackId);void RhythmSetKitName(int trackId, string name);+ /// <summary>Nota Rhythm macros: their names and mappings (the values are the macro1..8 plugin+ /// params). In a mapping, Chain is the voice; DeviceIndex -1 targets one of the Rhythm's own+ /// params (ParamIndex = its plugin-param index, 0..1), ≥ 0 a device on that voice's FX chain+ /// (the device's own units).</summary>+ string RhythmMacroName(int trackId, int macro);+ void RhythmSetMacroName(int trackId, int macro, string name);+ int RhythmAddMacroMapping(int trackId, int macro, int voice, int device, int param, float lo, float hi);+ int RhythmMacroMappingCount(int trackId);+ bool RhythmTryGetMacroMapping(int trackId, int index, out RackMacroMapping mapping, out int curve);+ bool RhythmRemoveMacroMapping(int trackId, int index);+ bool RhythmSetMacroMappingRange(int trackId, int index, float lo, float hi);+ bool RhythmSetMacroMappingCurve(int trackId, int index, int curve);+ /// <summary>Drops every mapping and custom name (the macro values stay).</summary>+ void RhythmClearMacros(int trackId);/// <summary>Live Nota Grain read positions (0..1) of active voices into outPos; returns the count.</summary>int GrainPlayPositions(int trackId, float[] outPos);/// <summary>Active synth-voice count for a built-in instrument, or -1 if unsupported.</summary>diff --git a/src/managed/Nota.Application/Instruments/RhythmModel.cs b/src/managed/Nota.Application/Instruments/RhythmModel.csindex 703fe58a..3daf2371 100644--- a/src/managed/Nota.Application/Instruments/RhythmModel.cs+++ b/src/managed/Nota.Application/Instruments/RhythmModel.cs@@ -27,9 +27,14 @@ public static class RhythmModelpublic const int S_Step = 0, S_Bank = 1, S_Rev = 2, S_Active = 3, S_Glue = 4, S_Flash0 = 5, S_Pos0 = S_Flash0 + Voices,ScopeLength = S_Pos0 + Voices;- // State magics: RTH1 carries the first 60 params, RTH2 all of them.- private const uint MagicV1 = 0x31485452, MagicV2 = 0x32485452;+ // State magics: RTH1 carries the first 60 params, RTH2 up to Glue, RTH3 all of them (+ the macros).+ private const uint MagicV1 = 0x31485452, MagicV2 = 0x32485452, MagicV3 = 0x33485452;public const int LegacyParams = Voices * 7 + 4;+ public const int Macros = 8;+ /// <summary>The param count of an RTH2 blob — everything before the macros.</summary>+ public const int ParamsV2 = LegacyParams + Voices * 3 + 1;+ /// <summary>Plugin-param id of macro <paramref name="m"/> (0-based).</summary>+ public static string MacroId(int m) => $"macro{m + 1}";public static readonly string[] VoiceNames = { "Kick", "Snare", "Clap", "Rim", "Closed Hat", "Open Hat", "Tom", "Perc" };public static readonly string[] ShortNames = { "KICK", "SNR", "CLAP", "RIM", "CH", "OH", "TOM", "PERC" };@@ -98,13 +103,14 @@ public static class RhythmModel}/// <summary>Read the blob: [magic][params][bank, voice, 2][on, vel, acc per bank/voice/step].- /// <paramref name="paramCount"/> is the instrument's current count (RTH2); an RTH1 blob holds 60.</summary>+ /// <paramref name="paramCount"/> is the instrument's current count (RTH3); RTH2 holds all but the+ /// macros, RTH1 the first 60.</summary>public static Pattern Parse(byte[] st, int paramCount){var p = new Pattern();if (st.Length < 4) return p;uint magic = BitConverter.ToUInt32(st, 0);- int n = magic == MagicV1 ? LegacyParams : magic == MagicV2 ? paramCount : -1;+ int n = magic == MagicV1 ? LegacyParams : magic == MagicV2 ? ParamsV2 : magic == MagicV3 ? paramCount : -1;if (n < 0) return p;int off = 4 + n * 4;if (off + 2 <= st.Length) { p.CurrentBank = Math.Min((int)st[off], Banks - 1); p.SelectedVoice = Math.Min((int)st[off + 1], Voices - 1); }@@ -174,5 +180,6 @@ public static class RhythmModel+ "reverse (≥ .5 plays the region backwards). Globals: swing (delays odd 16ths, 1 = half a step), humanize (velocity "+ "jitter), accent (how much louder an accented step plays, up to 2×), glue (bus compressor: 0 off … 1 heavy), "+ "volume (master). Steps: 16 per bar at 1/16 in four banks A–D; a step has a velocity 0..1 (below 0.45 it is a quiet "- + "step) and an accent flag. Closed Hat chokes Open Hat.";+ + "step) and an accent flag. Closed Hat chokes Open Hat. Macros macro1..macro8 (0..1): each drives its mapped targets "+ + "(voice params or params of a voice's FX devices) across their ranges; a factory kit sets them up.";}diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.csindex 170d3b6c..4da9688c 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs@@ -380,6 +380,35 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_rhythm_set_kit_name", StringMarshalling = StringMarshalling.Utf8)]internal static partial void RhythmSetKitName(IntPtr engine, int trackId, string name);+ // Nota Rhythm macros: names + mappings (the values are the macro1..8 plugin params).+ [LibraryImport(Lib, EntryPoint = "nota_rhythm_macro_name")]+ internal static partial IntPtr RhythmMacroName(IntPtr engine, int trackId, int macro);++ [LibraryImport(Lib, EntryPoint = "nota_rhythm_set_macro_name", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial void RhythmSetMacroName(IntPtr engine, int trackId, int macro, string name);++ [LibraryImport(Lib, EntryPoint = "nota_rhythm_add_macro_mapping")]+ internal static partial int RhythmAddMacroMapping(IntPtr engine, int trackId, int macro, int voice, int device, int param, float lo, float hi);++ [LibraryImport(Lib, EntryPoint = "nota_rhythm_macro_mapping_count")]+ internal static partial int RhythmMacroMappingCount(IntPtr engine, int trackId);++ [LibraryImport(Lib, EntryPoint = "nota_rhythm_macro_mapping_info")]+ internal static partial int RhythmMacroMappingInfo(IntPtr engine, int trackId, int index, out int macro, out int voice,+ out int device, out int param, out float lo, out float hi, out int curve);++ [LibraryImport(Lib, EntryPoint = "nota_rhythm_remove_macro_mapping")]+ internal static partial int RhythmRemoveMacroMapping(IntPtr engine, int trackId, int index);++ [LibraryImport(Lib, EntryPoint = "nota_rhythm_set_macro_mapping_range")]+ internal static partial int RhythmSetMacroMappingRange(IntPtr engine, int trackId, int index, float lo, float hi);++ [LibraryImport(Lib, EntryPoint = "nota_rhythm_set_macro_mapping_curve")]+ internal static partial int RhythmSetMacroMappingCurve(IntPtr engine, int trackId, int index, int curve);++ [LibraryImport(Lib, EntryPoint = "nota_rhythm_clear_macros")]+ internal static partial void RhythmClearMacros(IntPtr engine, int trackId);+[LibraryImport(Lib, EntryPoint = "nota_track_grain_play_positions")]internal static partial int TrackGrainPlayPositions(IntPtr engine, int trackId, [Out] float[] outPos, int maxN);diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.csindex 4a77148d..20da9d8f 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs@@ -717,6 +717,29 @@ public sealed partial class NotaEngine{ ThrowIfDisposed(); return System.Runtime.InteropServices.Marshal.PtrToStringUTF8(NativeMethods.RhythmKitName(_handle, trackId)) ?? ""; }public void RhythmSetKitName(int trackId, string name){ ThrowIfDisposed(); NativeMethods.RhythmSetKitName(_handle, trackId, name ?? ""); }+ public string RhythmMacroName(int trackId, int macro)+ { ThrowIfDisposed(); return System.Runtime.InteropServices.Marshal.PtrToStringUTF8(NativeMethods.RhythmMacroName(_handle, trackId, macro)) ?? ""; }+ public void RhythmSetMacroName(int trackId, int macro, string name)+ { ThrowIfDisposed(); NativeMethods.RhythmSetMacroName(_handle, trackId, macro, name ?? ""); }+ public int RhythmAddMacroMapping(int trackId, int macro, int voice, int device, int param, float lo, float hi)+ { ThrowIfDisposed(); return NativeMethods.RhythmAddMacroMapping(_handle, trackId, macro, voice, device, param, lo, hi); }+ public int RhythmMacroMappingCount(int trackId)+ { ThrowIfDisposed(); return NativeMethods.RhythmMacroMappingCount(_handle, trackId); }+ public bool RhythmTryGetMacroMapping(int trackId, int index, out RackMacroMapping mapping, out int curve)+ {+ ThrowIfDisposed();+ bool ok = NativeMethods.RhythmMacroMappingInfo(_handle, trackId, index, out int m, out int v, out int d, out int p, out float lo, out float hi, out curve) != 0;+ mapping = ok ? new RackMacroMapping(m, v, d, p, lo, hi) : default;+ return ok;+ }+ public bool RhythmRemoveMacroMapping(int trackId, int index)+ { ThrowIfDisposed(); return NativeMethods.RhythmRemoveMacroMapping(_handle, trackId, index) != 0; }+ public bool RhythmSetMacroMappingRange(int trackId, int index, float lo, float hi)+ { ThrowIfDisposed(); return NativeMethods.RhythmSetMacroMappingRange(_handle, trackId, index, lo, hi) != 0; }+ public bool RhythmSetMacroMappingCurve(int trackId, int index, int curve)+ { ThrowIfDisposed(); return NativeMethods.RhythmSetMacroMappingCurve(_handle, trackId, index, curve) != 0; }+ public void RhythmClearMacros(int trackId)+ { ThrowIfDisposed(); NativeMethods.RhythmClearMacros(_handle, trackId); }public int GrainPlayPositions(int trackId, float[] outPos){ ThrowIfDisposed(); return NativeMethods.TrackGrainPlayPositions(_handle, trackId, outPos, outPos.Length); }diff --git a/src/managed/Nota.Infrastructure/Kits/DrumKitService.cs b/src/managed/Nota.Infrastructure/Kits/DrumKitService.csindex b2282417..e602a915 100644--- a/src/managed/Nota.Infrastructure/Kits/DrumKitService.cs+++ b/src/managed/Nota.Infrastructure/Kits/DrumKitService.cs@@ -4,7 +4,7 @@// IDrumKits over the code-defined kit catalog: renders a kit's one-shots on demand// (KitLibrary) and assembles a Drum Rack from them — one Sampler chain per pad, with// the pad's trigger note, choke group, pan, gain, name and effects (KitFx), plus the-// kit's swing and humanize. Loading a kit is an ordinary sequence of engine calls, so the+// kit's swing, humanize and macros (KitMacros). Loading a kit is an ordinary sequence of engine calls, so the// result is an ordinary Drum Rack the user can take apart pad by pad.//// The same kits load into Nota Rhythm: each of its eight voices takes the kit's pad on the@@ -120,6 +120,7 @@ public sealed class DrumKitService : IDrumKitsKitLibrary.Ensure(kit);var missing = new List<string>();+ var loaded = new List<(int Slot, KitPad Pad)>();foreach (var pad in kit.Pads){var path = KitLibrary.PathOf(kit, pad);@@ -139,10 +140,12 @@ public sealed class DrumKitService : IDrumKitsKitFx.Apply(KitFx.For(kit, pad), k => engine.RackAddChainDevice(track, c, k),d => engine.RackChainDeviceParamCount(track, c, d), (d, p) => engine.RackChainDeviceParamName(track, c, d, p),(d, p, v) => engine.RackChainDeviceParamSet(track, c, d, p, v));+ loaded.Add((chain, pad));}engine.RackSetSwing(track, kit.Swing);engine.RackSetHumanize(track, kit.Humanize);+ ApplyRackMacros(engine, track, kit, loaded);warning = missing.Count == 0? ""@@ -175,7 +178,9 @@ public sealed class DrumKitService : IDrumKitsvoid Set(string id, float v) { if (idx.TryGetValue(id, out int i)) engine.PluginParamSet(track, -1, i, v); }var missing = new List<string>();+ var loaded = new List<(int Slot, KitPad Pad)>();var pads = RhythmVoicePads(kit);+ engine.RhythmClearMacros(track); // the old kit's mappings would point at devices about to gofor (int v = 0; v < RhythmModel.Voices; v++){while (engine.RhythmVoiceDeviceCount(track, v) > 0) engine.RhythmRemoveVoiceDevice(track, v, 0);@@ -195,16 +200,97 @@ public sealed class DrumKitService : IDrumKitsKitFx.Apply(KitFx.For(kit, pad), k => engine.RhythmAddVoiceDevice(track, vv, k),d => engine.RhythmVoiceDeviceParamCount(track, vv, d), (d, p) => engine.RhythmVoiceDeviceParamName(track, vv, d, p),(d, p, x) => engine.RhythmVoiceDeviceParamSet(track, vv, d, p, x));+ loaded.Add((v, pad));}Set("swing", kit.Swing);Set("humanize", kit.Humanize);engine.RhythmSetKitName(track, kit.Id);+ ApplyRhythmMacros(engine, track, kit, loaded, idx);warning = missing.Count == 0? "": $"{kit.Name}: {missing.Count} voice(s) couldn't be loaded ({string.Join(", ", missing)}).";}+ // ---- macros -----------------------------------------------------------------------------++ // The kit's macros on a Drum Rack: names and values first, then the mappings (a mapping applies+ // its macro's value at once, and every range puts that value on the pad's current setting).+ // Pad Tune / Decay are the pad's own controls; the effects are the pad chain's devices.+ private static void ApplyRackMacros(IAudioEngine engine, int track, KitDefinition kit, List<(int Slot, KitPad Pad)> pads)+ {+ var (macros, plan) = KitMacros.Resolve(kit, pads,+ t => t.Param switch+ {+ MacroParam.Tune => engine.RackChainTune(track, t.Slot),+ MacroParam.Decay => engine.RackChainDecay(track, t.Slot),+ _ => engine.RackChainDeviceParamGet(track, t.Slot, t.Device, t.FxParamIndex),+ },+ (chain, kind, name) => FindFx(kind, name, engine.RackChainDeviceCount(track, chain),+ d => engine.RackChainDeviceBuiltinKind(track, chain, d), d => engine.RackChainDeviceParamCount(track, chain, d),+ (d, p) => engine.RackChainDeviceParamName(track, chain, d, p)));+ for (int m = 0; m < KitMacros.Count; m++)+ {+ var km = macros.FirstOrDefault(x => x.Slot == m);+ engine.RackSetMacroName(track, m, km?.Name ?? "");+ engine.RackMacroSet(track, m, km?.Value ?? 0f);+ }+ foreach (var it in plan)+ {+ var t = it.Target;+ if (t.Param == MacroParam.Fx) engine.RackAddMacroMapping(track, it.Macro, t.Slot, t.Device, t.FxParamIndex, it.Lo, it.Hi);+ else engine.RackAddMacroMapping(track, it.Macro, t.Slot, RackMacroMapping.PadControls,+ t.Param == MacroParam.Tune ? RackMacroMapping.PadTune : RackMacroMapping.PadDecay, it.Lo, it.Hi);+ }+ }++ // The kit's macros on a Rhythm: the voices' Tune / Decay params (Tune given in semitones —+ // a sample voice's ±12 st over 0..1) and the voices' FX. The macro values are its macro1..8.+ private static void ApplyRhythmMacros(IAudioEngine engine, int track, KitDefinition kit, List<(int Slot, KitPad Pad)> voices,+ Dictionary<string, int> idx)+ {+ int P(int v, MacroParam p) => idx.TryGetValue(RhythmModel.Id(v, p == MacroParam.Tune ? "tune" : "decay"), out int i) ? i : -1;+ var (macros, plan) = KitMacros.Resolve(kit, voices,+ t => t.Param switch+ {+ MacroParam.Tune => RhythmModel.SampleSemis(engine.PluginParamGet(track, -1, P(t.Slot, t.Param))),+ MacroParam.Decay => engine.PluginParamGet(track, -1, P(t.Slot, t.Param)),+ _ => engine.RhythmVoiceDeviceParamGet(track, t.Slot, t.Device, t.FxParamIndex),+ },+ (v, kind, name) => FindFx(kind, name, engine.RhythmVoiceDeviceCount(track, v),+ d => engine.RhythmVoiceDeviceBuiltinKind(track, v, d), d => engine.RhythmVoiceDeviceParamCount(track, v, d),+ (d, p) => engine.RhythmVoiceDeviceParamName(track, v, d, p)));+ for (int m = 0; m < KitMacros.Count; m++)+ {+ var km = macros.FirstOrDefault(x => x.Slot == m);+ engine.RhythmSetMacroName(track, m, km?.Name ?? "");+ if (idx.TryGetValue(RhythmModel.MacroId(m), out int mi)) engine.PluginParamSet(track, -1, mi, km?.Value ?? 0f);+ }+ foreach (var it in plan)+ {+ var t = it.Target;+ if (t.Param == MacroParam.Fx) { engine.RhythmAddMacroMapping(track, it.Macro, t.Slot, t.Device, t.FxParamIndex, it.Lo, it.Hi); continue; }+ int p = P(t.Slot, t.Param);+ if (p < 0) continue;+ float lo = it.Lo, hi = it.Hi;+ if (t.Param == MacroParam.Tune) { lo = RhythmModel.SampleSemisNorm(lo); hi = RhythmModel.SampleSemisNorm(hi); }+ engine.RhythmAddMacroMapping(track, it.Macro, t.Slot, -1, p, lo, hi);+ }+ }++ // A chain's first device of a built-in kind, and a param of it by name.+ private static (int, int) FindFx(int kind, string param, int count, Func<int, int> kindOf, Func<int, int> paramCount, Func<int, int, string> paramName)+ {+ for (int d = 0; d < count; d++)+ {+ if (kindOf(d) != kind) continue;+ int n = paramCount(d);+ for (int p = 0; p < n; p++) if (paramName(d, p) == param) return (d, p);+ return (d, -1);+ }+ return (-1, -1);+ }+/// <summary>A kit voice's Level: the kit's own gain on the headroom Rhythm leaves a voice.</summary>private const float RhythmLevel = 0.8f;}diff --git a/src/managed/Nota.Infrastructure/Kits/KitFx.cs b/src/managed/Nota.Infrastructure/Kits/KitFx.csindex 88ef081c..752b5cda 100644--- a/src/managed/Nota.Infrastructure/Kits/KitFx.cs+++ b/src/managed/Nota.Infrastructure/Kits/KitFx.cs@@ -158,8 +158,9 @@ public static class KitFx// The devices' exponential knobs: value = lo · (hi / lo)^norm.private static float Exp(double v, double lo, double hi) => (float)Math.Clamp(Math.Log(v / lo) / Math.Log(hi / lo), 0, 1);- // Dry gain is (1 - mix) · 2 · level²; this level keeps it at 1.- private static float UnityDry(double mix) => (float)Math.Clamp(Math.Sqrt(0.5 / (1 - mix)), 0, 1);+ /// <summary>The Dry Level that keeps a reverb's or delay's dry at unity for a given mix: dry+ /// gain is (1 - mix) · 2 · level².</summary>+ public static float UnityDry(double mix) => (float)Math.Clamp(Math.Sqrt(0.5 / (1 - mix)), 0, 1);/// <summary>Builds <paramref name="fx"/> through a chain's device surface: <paramref name="add"/>/// appends a device of a kind and returns its index (-1 on failure); the rest address thediff --git a/src/managed/Nota.Infrastructure/Kits/KitMacros.cs b/src/managed/Nota.Infrastructure/Kits/KitMacros.csnew file mode 100644index 00000000..694d2651--- /dev/null+++ b/src/managed/Nota.Infrastructure/Kits/KitMacros.cs@@ -0,0 +1,146 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The factory kits' macros: the eight knobs a kit loads with, on the Drum Rack and on Nota+// Rhythm alike. A macro drives the pads it names by their role in the kit — a pad control (its+// Tune or Decay) or a param of the pad's own effects (KitFx), so one knob opens every snare and+// clap reverb at once.+//+// 1 Tune every pad but the bass, ±12 st (±5 on the acoustic and hand-percussion kits).+// 2 Decay the drums that ring out (kick, snare, clap, toms, percussion): full length at+// the top, a tight gate at the bottom — how far down depends on the kit.+// 3 Hats the hats' decay, on its own knob so the groove's length stays separate.+// 4 Drive/Tape the kick's parallel saturation (Forge drive and amount).+// 5 Room/Space the snare and clap reverbs: level and decay.+// 6 Echo/Dub the hat and percussion delays: level and feedback.+// 7 808/Sub the tuned bass pads' pitch, on kits that have them.+// 8 left free for the user.+//+// A macro whose targets the kit doesn't have (no reverb on a baked-room snare, no bass pad)+// stays unassigned. Every range is built around the value the kit loads with, so a freshly+// loaded kit sounds exactly as its recipe — the macro sits at that value: Tune in the middle,+// Decay and Hats at the top (full length), the effect macros in the middle, with room to go+// both ways.++using System;+using System.Collections.Generic;+using System.Linq;++namespace Nota.Infrastructure.Kits;++/// <summary>What a macro rule drives on a pad: a pad control, or a param of one of its effects.</summary>+public enum MacroParam { Tune, Decay, Fx }++/// <summary>One kind of target of a kit macro: the pads with one of <paramref name="Roles"/>, the+/// <paramref name="Param"/> (for Fx: <paramref name="FxParam"/> of the pad's device of kind+/// <paramref name="FxKind"/>). <paramref name="Range"/> turns the target's value at load, in its+/// own units (semitones for Tune, 0..1 for Decay, the device's units for Fx), into the mapping's+/// [lo, hi].</summary>+public sealed record MacroRule(PadRole[] Roles, MacroParam Param, Func<double, (double Lo, double Hi)> Range,+ int FxKind = -1, string FxParam = "");++/// <summary>A kit macro: its slot (0..7), name, the value it loads at, and what it drives.</summary>+public sealed record KitMacro(int Slot, string Name, float Value, IReadOnlyList<MacroRule> Rules);++/// <summary>One mapping of a kit macro, resolved on an instrument: macro <paramref name="Macro"/>+/// drives <paramref name="Target"/> over [lo, hi].</summary>+public readonly record struct MacroPlanItem(int Macro, MacroTarget Target, float Lo, float Hi);++/// <summary>A concrete macro target on a kit instrument: pad/voice <paramref name="Slot"/>,+/// its <paramref name="Param"/>, and for Fx the device index and param index.</summary>+public readonly record struct MacroTarget(int Slot, MacroParam Param, int Device = -1, int FxParamIndex = -1);++public static class KitMacros+{+ public const int Count = 8;++ private static readonly PadRole[] Every = Enum.GetValues<PadRole>().Where(r => r != PadRole.Sub).ToArray(); // the bass stays in key: it has its own+ private static readonly PadRole[] Ringing = { PadRole.Kick, PadRole.Snare, PadRole.Clap, PadRole.Tom, PadRole.Perc };+ private static readonly PadRole[] Hats = { PadRole.ClosedHat, PadRole.OpenHat };+ private static readonly PadRole[] Kicks = { PadRole.Kick };+ private static readonly PadRole[] Spaced = { PadRole.Snare, PadRole.Clap };+ private static readonly PadRole[] Echoed = { PadRole.ClosedHat, PadRole.OpenHat, PadRole.Perc };+ private static readonly PadRole[] Subs = { PadRole.Sub };++ /// <summary>The macros <paramref name="kit"/> loads with, by slot.</summary>+ public static IReadOnlyList<KitMacro> For(KitDefinition kit)+ {+ // The kit's character: how far the pitch goes, how short the gate gets, and what the+ // effect knobs are called.+ bool acoustic = kit.Id is "atelier" or "terra" or "velvet" or "brass-room" or "pit" or "lagoon";+ double semis = acoustic ? 5 : 12;+ double floor = kit.Id switch+ {+ "aether" or "titan" or "volta" or "yard" => 0.15, // long tails: the knob can go a long way+ "pixel" or "byte" or "micron" => 0.35, // already short: keep a hit a hit+ _ => 0.25,+ };+ bool bigSpace = kit.FxSpace >= 1.3;+ bool eightOhEight = kit.Pads.Any(p => KitFx.RoleOf(p) == PadRole.Sub && p.Name.StartsWith("808", StringComparison.Ordinal));++ return new List<KitMacro>+ {+ new(0, "Tune", 0.5f, new[] { new MacroRule(Every, MacroParam.Tune, cur => (cur - semis, cur + semis)) }),+ new(1, "Decay", 1f, new[] { new MacroRule(Ringing, MacroParam.Decay, cur => (Math.Min(floor, cur), cur)) }),+ new(2, "Hats", 1f, new[] { new MacroRule(Hats, MacroParam.Decay, cur => (Math.Min(0.15, cur), cur)) }),+ new(3, kit.FxTape ? "Tape" : "Drive", 0.5f, new[]+ {+ Fx(Kicks, KitFx.Forge, "S1 Drive", cur => AroundFrom(0, cur)),+ Fx(Kicks, KitFx.Forge, "Amount", cur => AroundFrom(0, cur)),+ }),+ new(4, bigSpace ? "Space" : "Room", 0.5f, new[]+ {+ Fx(Spaced, KitFx.Reverb, "Dry/Wet", cur => AroundFrom(0, cur)),+ Fx(Spaced, KitFx.Reverb, "Dry Level", cur => AroundFrom(KitFx.UnityDry(0), cur)), // the dry stays near unity+ Fx(Spaced, KitFx.Reverb, "Decay", cur => AroundFrom(Math.Max(0, cur - 0.2), cur)),+ }),+ new(5, kit.Id == "yard" ? "Dub" : "Echo", 0.5f, new[]+ {+ Fx(Echoed, KitFx.Delay, "Dry/Wet", cur => AroundFrom(0, cur)),+ Fx(Echoed, KitFx.Delay, "Dry Level", cur => AroundFrom(KitFx.UnityDry(0), cur)),+ Fx(Echoed, KitFx.Delay, "Feedback", cur => AroundFrom(0, cur)),+ }),+ new(6, eightOhEight ? "808" : "Sub", 0.5f, new[] { new MacroRule(Subs, MacroParam.Tune, cur => (cur - 12, cur + 12)) }),+ };+ }++ private static MacroRule Fx(PadRole[] roles, int kind, string param, Func<double, (double, double)> range)+ => new(roles, MacroParam.Fx, range, kind, param);++ // A range from `lo` whose midpoint is `cur`: the macro loads at 0.5 on the kit's own value+ // and goes as far past it as it goes below.+ private static (double, double) AroundFrom(double lo, double cur) => (lo, lo + (cur - lo) * 2);++ /// <summary>Resolves the kit's macros on an instrument. <paramref name="pads"/> lists the+ /// instrument's slots (pad chains or Rhythm voices) with the kit pad each holds;+ /// <paramref name="current"/> reads a target's value at load (in the rule's units, see+ /// <see cref="MacroRule"/>), <paramref name="findFx"/> finds a slot's device of a kind and a+ /// param of it by name ((-1, -1) = none). Macros that end up with no target are dropped.</summary>+ public static (IReadOnlyList<KitMacro> Macros, IReadOnlyList<MacroPlanItem> Plan) Resolve(+ KitDefinition kit, IReadOnlyList<(int Slot, KitPad Pad)> pads,+ Func<MacroTarget, double> current, Func<int, int, string, (int Device, int Param)> findFx)+ {+ var used = new List<KitMacro>();+ var plan = new List<MacroPlanItem>();+ foreach (var macro in For(kit))+ {+ int before = plan.Count;+ foreach (var rule in macro.Rules)+ foreach (var (slot, pad) in pads)+ {+ if (Array.IndexOf(rule.Roles, KitFx.RoleOf(pad)) < 0) continue;+ var target = new MacroTarget(slot, rule.Param);+ if (rule.Param == MacroParam.Fx)+ {+ var (dev, p) = findFx(slot, rule.FxKind, rule.FxParam);+ if (dev < 0 || p < 0) continue;+ target = target with { Device = dev, FxParamIndex = p };+ }+ var (lo, hi) = rule.Range(current(target));+ plan.Add(new MacroPlanItem(macro.Slot, target, (float)lo, (float)hi));+ }+ if (plan.Count > before) used.Add(macro);+ }+ return (used, plan);+ }+}diff --git a/src/managed/Nota.Mcp/Tools/RackTools.cs b/src/managed/Nota.Mcp/Tools/RackTools.csindex 275f6e18..5daf767f 100644--- a/src/managed/Nota.Mcp/Tools/RackTools.cs+++ b/src/managed/Nota.Mcp/Tools/RackTools.cs@@ -124,8 +124,10 @@ public sealed class RackTools(IAudioEngine engine, IEngineDispatch dispatch, IAr});[McpServerTool(Name = "add_macro_mapping"), Description(- "Map a macro (0..7) onto a parameter. deviceIndex = -1 targets the chain instrument, else the "- + "chain's device index. range is the param's normalized 0..1 span the macro sweeps. Returns mapping index.")]+ "Map a macro (0..7) onto a parameter. deviceIndex = -1 targets the chain instrument, -2 the chain's own controls "+ + "(a Drum Rack pad: paramIndex 0 Volume (linear gain), 1 Pan (-1..1), 2 Tune (semitones), 3 Decay (0..1, 1 = hold)), "+ + "else the chain's device index (a built-in effect on the pad; range in the device's units). range is the span the "+ + "macro sweeps, in the target's units (0..1 for an instrument param). Returns mapping index.")]public Task<int> AddMacroMapping(int trackId, int macro, int chain, int deviceIndex, int paramIndex, float rangeMin = 0f, float rangeMax = 1f)=> Mutate(() => E.RackAddMacroMapping(trackId, macro, chain, deviceIndex, paramIndex, rangeMin, rangeMax));diff --git a/src/managed/Nota.Mcp/Tools/RhythmTools.cs b/src/managed/Nota.Mcp/Tools/RhythmTools.csindex dd129dec..4271d652 100644--- a/src/managed/Nota.Mcp/Tools/RhythmTools.cs+++ b/src/managed/Nota.Mcp/Tools/RhythmTools.cs@@ -8,7 +8,8 @@// Decay / Punch / Tone / Drive / Level / Pan, and for a sample voice Start / Length / Reverse)// and the groove (Swing / Humanize / Accent / Glue / Volume) are plugin parameters — set them with// set_rhythm_voice / set_rhythm_perform, or get_instrument_params / set_instrument_param_by_id.-// A voice plays its built-in synth engine or a loaded one-shot sample.+// A voice plays its built-in synth engine or a loaded one-shot sample. Eight macros drive voice+// params and the voices' effects (get_rhythm_macros / set_rhythm_macro / map_rhythm_macro).using System.ComponentModel;using System.Text;@@ -188,6 +189,84 @@ public sealed class RhythmTools(IAudioEngine engine, IEngineDispatch dispatch, Ireturn VoiceLine(trackId, v);});+ public sealed record RhythmMacro(int Index, string Name, float Value, RhythmMacroTarget[] Targets);+ public sealed record RhythmMacroTarget(int Mapping, string Voice, string Target, float RangeMin, float RangeMax, int Device, int Param);++ [McpServerTool(Name = "get_rhythm_macros"), Description(+ "The Rhythm's eight macros: name, value 0..1 and every target — a voice param (device -1, param = its plugin-param "+ + "index, range 0..1) or a param of a voice's effect (device ≥ 0, range in the device's units). A factory kit loads "+ + "its own (Tune, Decay, Hats, Drive/Tape, Room, Echo, 808 …).")]+ public Task<RhythmMacro[]> GetRhythmMacros(int trackId) => Read(() =>+ {+ var ids = Ids(trackId);+ var all = new List<RhythmMacro>();+ int n = E.RhythmMacroMappingCount(trackId);+ for (int m = 0; m < RM.Macros; m++)+ {+ var targets = new List<RhythmMacroTarget>();+ for (int i = 0; i < n; i++)+ {+ if (!E.RhythmTryGetMacroMapping(trackId, i, out var mm, out _) || mm.Macro != m) continue;+ string what = mm.DeviceIndex < 0 ? E.PluginParamId(trackId, -1, mm.ParamIndex)+ : $"{E.RhythmVoiceDeviceName(trackId, mm.Chain, mm.DeviceIndex)} › {E.RhythmVoiceDeviceParamName(trackId, mm.Chain, mm.DeviceIndex, mm.ParamIndex)}";+ targets.Add(new RhythmMacroTarget(i, mm.Chain >= 0 ? RM.VoiceNames[mm.Chain] : "kit", what, mm.RangeMin, mm.RangeMax, mm.DeviceIndex, mm.ParamIndex));+ }+ float val = ids.TryGetValue(RM.MacroId(m), out var pi) ? E.PluginParamGet(trackId, -1, pi) : 0f;+ all.Add(new RhythmMacro(m, E.RhythmMacroName(trackId, m), val, targets.ToArray()));+ }+ return all.ToArray();+ });++ [McpServerTool(Name = "set_rhythm_macro"), Description("Turn a Rhythm macro (0..7) to value 0..1 (drives every target), and/or rename it.")]+ public Task<string> SetRhythmMacro(int trackId, int macro, float? value = null, string? name = null) => Mutate(() =>+ {+ if (E.TrackInstrumentKind(trackId) != RM.Kind) return $"error: track {trackId} is not a Nota Rhythm";+ if (macro is < 0 or >= RM.Macros) return "error: macro 0..7";+ if (name is not null) E.RhythmSetMacroName(trackId, macro, name);+ if (value is { } v && Ids(trackId).TryGetValue(RM.MacroId(macro), out var pi)) E.PluginParamSet(trackId, -1, pi, Math.Clamp(v, 0f, 1f));+ return $"{E.RhythmMacroName(trackId, macro)}";+ });++ [McpServerTool(Name = "map_rhythm_macro"), Description(+ "Map a Rhythm macro (0..7) onto a target. Voice param: voice = 0..7 or its name, param = the param id suffix "+ + "(tune, decay, punch, tone, drive, level, pan, start, length), device omitted; a kit setting: voice = kit, param = "+ + "swing | humanize | accent | glue | volume. A voice effect: device = its index on the voice's FX chain, param = the "+ + "device's param name (e.g. Dry/Wet). rangeMin/rangeMax: the span swept (0..1 for voice params, device units for "+ + "effects; omitted = the whole param). Returns the mapping index or an error.")]+ public Task<string> MapRhythmMacro(int trackId, int macro, string voice, string param, int device = -1,+ float? rangeMin = null, float? rangeMax = null) => Mutate(() =>+ {+ if (E.TrackInstrumentKind(trackId) != RM.Kind) return $"error: track {trackId} is not a Nota Rhythm";+ bool kit = voice.Trim().Equals("kit", StringComparison.OrdinalIgnoreCase);+ int v = kit ? -1 : VoiceIndex(voice);+ if (!kit && v < 0) return $"error: voice '{voice}'";+ int p; float lo = rangeMin ?? 0f, hi = rangeMax ?? 1f;+ if (device < 0)+ {+ if (!Ids(trackId).TryGetValue(kit ? param : RM.Id(v, param), out p)) return $"error: no param '{param}'";+ }+ else+ {+ if (kit || device >= E.RhythmVoiceDeviceCount(trackId, v)) return $"error: voice {voice} has no effect {device}";+ p = Enumerable.Range(0, E.RhythmVoiceDeviceParamCount(trackId, v, device)).FirstOrDefault(i => E.RhythmVoiceDeviceParamName(trackId, v, device, i) == param, -1);+ if (p < 0) return $"error: {E.RhythmVoiceDeviceName(trackId, v, device)} has no '{param}'";+ lo = rangeMin ?? E.RhythmVoiceDeviceParamMin(trackId, v, device, p);+ hi = rangeMax ?? E.RhythmVoiceDeviceParamMax(trackId, v, device, p);+ }+ int idx = E.RhythmAddMacroMapping(trackId, macro, v, device, p, lo, hi);+ return idx >= 0 ? idx.ToString() : "error: could not map";+ });++ [McpServerTool(Name = "unmap_rhythm_macro"), Description("Remove a Rhythm macro mapping by its index (from get_rhythm_macros), or every mapping of a macro with macro = 0..7 and index = -1.")]+ public Task<int> UnmapRhythmMacro(int trackId, int index = -1, int macro = -1) => Mutate(() =>+ {+ if (index >= 0) return E.RhythmRemoveMacroMapping(trackId, index) ? 1 : 0;+ int removed = 0;+ for (int i = E.RhythmMacroMappingCount(trackId) - 1; i >= 0; i--)+ if (E.RhythmTryGetMacroMapping(trackId, i, out var m, out _) && m.Macro == macro && E.RhythmRemoveMacroMapping(trackId, i)) removed++;+ return removed;+ });+[McpServerTool(Name = "set_rhythm_perform"), Description("Set the Rhythm groove and bus; every argument optional, all 0..1: swing (delays every second 16th, 1 = half a step), "+ "humanize (velocity jitter), accent (how much louder accented steps play), glue (bus compressor, 0 = off), "diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex b64d478c..25cd5f0a 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -422,6 +422,21 @@ NOTA_API int32_t nota_rhythm_voice_device_bypassed(const NotaEngine* engine,NOTA_API void nota_rhythm_set_voice_device_bypassed(NotaEngine* engine, int32_t track_id, int32_t voice, int32_t dev, int32_t bypassed);NOTA_API const char* nota_rhythm_kit_name(const NotaEngine* engine, int32_t track_id);NOTA_API void nota_rhythm_set_kit_name(NotaEngine* engine, int32_t track_id, const char* name);+/* Nota Rhythm macros. The eight values are the instrument's macro1..macro8 plugin params; these edit+ * their names and mappings. A mapping drives a target over [lo, hi] in the target's own units: device+ * -1 = one of the Rhythm's own params (param = its plugin-param index, 0..1), device >= 0 = param of+ * that device on voice's FX chain. add returns the mapping index or -1; clear drops every mapping and+ * name (the values stay). */+NOTA_API const char* nota_rhythm_macro_name(const NotaEngine* engine, int32_t track_id, int32_t macro);+NOTA_API void nota_rhythm_set_macro_name(NotaEngine* engine, int32_t track_id, int32_t macro, const char* name);+NOTA_API int32_t nota_rhythm_add_macro_mapping(NotaEngine* engine, int32_t track_id, int32_t macro, int32_t voice, int32_t device, int32_t param, float lo, float hi);+NOTA_API int32_t nota_rhythm_macro_mapping_count(const NotaEngine* engine, int32_t track_id);+NOTA_API int32_t nota_rhythm_macro_mapping_info(const NotaEngine* engine, int32_t track_id, int32_t index, int32_t* macro, int32_t* voice,+ int32_t* device, int32_t* param, float* lo, float* hi, int32_t* curve);+NOTA_API int32_t nota_rhythm_remove_macro_mapping(NotaEngine* engine, int32_t track_id, int32_t index);+NOTA_API int32_t nota_rhythm_set_macro_mapping_range(NotaEngine* engine, int32_t track_id, int32_t index, float lo, float hi);+NOTA_API int32_t nota_rhythm_set_macro_mapping_curve(NotaEngine* engine, int32_t track_id, int32_t index, int32_t curve);+NOTA_API void nota_rhythm_clear_macros(NotaEngine* engine, int32_t track_id);/* Adds an instrument track with the built-in sampler loaded from a file.* Returns id (>0), or 0 on failure (decode error). */NOTA_API int32_t nota_engine_add_sampler_track(NotaEngine* engine, const char* path_utf8,diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.hindex 35a7254a..d7504cd6 100644--- a/src/native/nota.engine/src/Engine.h+++ b/src/native/nota.engine/src/Engine.h@@ -527,6 +527,17 @@ public:Device* rhythmVoiceDevice(int32_t trackId, int32_t voice, int32_t dev) const;std::string rhythmKitName(int32_t trackId) const;void setRhythmKitName(int32_t trackId, const std::string& name);+ // Nota Rhythm macros: names + mappings (the values are the macro1..8 plugin params).+ std::string rhythmMacroName(int32_t trackId, int32_t macro) const;+ void setRhythmMacroName(int32_t trackId, int32_t macro, const std::string& name);+ int32_t rhythmAddMacroMapping(int32_t trackId, int32_t macro, int32_t voice, int32_t device, int32_t param, float lo, float hi);+ int32_t rhythmMacroMappingCount(int32_t trackId) const;+ bool rhythmMacroMappingInfo(int32_t trackId, int32_t index, int32_t& macro, int32_t& voice, int32_t& device,+ int32_t& param, float& lo, float& hi, int32_t& curve) const;+ bool rhythmRemoveMacroMapping(int32_t trackId, int32_t index);+ bool rhythmSetMacroMappingRange(int32_t trackId, int32_t index, float lo, float hi);+ bool rhythmSetMacroMappingCurve(int32_t trackId, int32_t index, int32_t curve);+ void rhythmClearMacros(int32_t trackId);bool setTrackGrainSample(int32_t trackId, const std::string& path, int32_t rootNote);int32_t addSamplerTrack(const std::string& path, int32_t rootNote, bool loop);int32_t addSamplerInstrumentTrack(); // empty Sampler (sample loaded later)diff --git a/src/native/nota.engine/src/Engine_Tracks.cpp b/src/native/nota.engine/src/Engine_Tracks.cppindex d09d1c80..ce517f33 100644--- a/src/native/nota.engine/src/Engine_Tracks.cpp+++ b/src/native/nota.engine/src/Engine_Tracks.cpp@@ -617,6 +617,38 @@ std::string Engine::rhythmKitName(int32_t trackId) const {void Engine::setRhythmKitName(int32_t trackId, const std::string& name) {if (auto* rh = rhythmOf(findTrackAuthoring(trackId))) rh->setKitName(name);}+std::string Engine::rhythmMacroName(int32_t trackId, int32_t macro) const {+ auto* rh = rhythmOf(findTrackAuthoring(trackId)); return rh ? rh->macroName(macro) : std::string{};+}+void Engine::setRhythmMacroName(int32_t trackId, int32_t macro, const std::string& name) {+ if (auto* rh = rhythmOf(findTrackAuthoring(trackId))) rh->setMacroName(macro, name);+}+int32_t Engine::rhythmAddMacroMapping(int32_t trackId, int32_t macro, int32_t voice, int32_t device, int32_t param, float lo, float hi) {+ auto* rh = rhythmOf(findTrackAuthoring(trackId)); return rh ? rh->addMacroMapping(macro, voice, device, param, lo, hi) : -1;+}+int32_t Engine::rhythmMacroMappingCount(int32_t trackId) const {+ auto* rh = rhythmOf(findTrackAuthoring(trackId)); return rh ? rh->macroMappingCount() : 0;+}+bool Engine::rhythmMacroMappingInfo(int32_t trackId, int32_t index, int32_t& macro, int32_t& voice, int32_t& device,+ int32_t& param, float& lo, float& hi, int32_t& curve) const {+ auto* rh = rhythmOf(findTrackAuthoring(trackId));+ RhythmMachine::MacroMap m;+ if (!rh || !rh->macroMapping(index, m)) return false;+ macro = m.macro; voice = m.voice; device = m.device; param = m.param; lo = m.lo; hi = m.hi; curve = m.curve;+ return true;+}+bool Engine::rhythmRemoveMacroMapping(int32_t trackId, int32_t index) {+ auto* rh = rhythmOf(findTrackAuthoring(trackId)); return rh && rh->removeMacroMapping(index);+}+bool Engine::rhythmSetMacroMappingRange(int32_t trackId, int32_t index, float lo, float hi) {+ auto* rh = rhythmOf(findTrackAuthoring(trackId)); return rh && rh->setMacroMappingRange(index, lo, hi);+}+bool Engine::rhythmSetMacroMappingCurve(int32_t trackId, int32_t index, int32_t curve) {+ auto* rh = rhythmOf(findTrackAuthoring(trackId)); return rh && rh->setMacroMappingCurve(index, curve);+}+void Engine::rhythmClearMacros(int32_t trackId) {+ if (auto* rh = rhythmOf(findTrackAuthoring(trackId))) rh->clearMacros();+}int32_t Engine::grainPlayPositions(int32_t trackId, float* out, int32_t maxN) const {if (!out || maxN <= 0) return 0;diff --git a/src/native/nota.engine/src/RackCore.h b/src/native/nota.engine/src/RackCore.hindex d418371a..bb56fe90 100644--- a/src/native/nota.engine/src/RackCore.h+++ b/src/native/nota.engine/src/RackCore.h@@ -89,13 +89,24 @@ public:struct MacroMapping {int32_t macro = 0;int32_t chainIndex = 0;- int32_t deviceIndex = -1; // -1 = the chain's instrument, else a device+ int32_t deviceIndex = -1; // -1 = the chain's instrument, kPadControls = the pad itself, else a deviceint32_t paramIndex = 0;float rangeMin = 0.0f;float rangeMax = 1.0f;int32_t curve = 0; // 0 Linear, 1 Exp, 2 Log, 3 S-curve};+ // A mapping with this deviceIndex targets the chain's own controls (a Drum Rack pad's+ // strip) rather than a child: paramIndex is a PadParam, in the control's own units.+ static constexpr int32_t kPadControls = -2;+ enum PadParam : int32_t { PadVolume = 0, PadPan, PadTune, PadDecay, kPadParams };+ static const char* padParamName(int32_t p) {+ static const char* n[kPadParams] = { "Volume", "Pan", "Tune", "Decay" };+ return (p >= 0 && p < kPadParams) ? n[p] : "";+ }+ static float padParamMin(int32_t p) { return p == PadPan ? -1.0f : p == PadTune ? -48.0f : 0.0f; }+ static float padParamMax(int32_t p) { return p == PadVolume ? 2.0f : p == PadTune ? 48.0f : 1.0f; }+struct RackState {std::vector<RackChain> chains;std::vector<MacroMapping> mappings;@@ -264,6 +275,13 @@ public:auto& d = ns->chains[chain].devices;if (dev < 0 || dev >= static_cast<int32_t>(d.size())) return false;d.erase(d.begin() + dev);+ // Mappings follow their device: the removed one's go, the ones after it shift down.+ auto& mv = ns->mappings;+ for (auto it = mv.begin(); it != mv.end();) {+ if (it->chainIndex == chain && it->deviceIndex == dev) { it = mv.erase(it); continue; }+ if (it->chainIndex == chain && it->deviceIndex > dev) --it->deviceIndex;+ ++it;+ }commit(ns);return true;}@@ -278,6 +296,12 @@ public:auto x = d[from];d.erase(d.begin() + from);d.insert(d.begin() + to, x);+ for (auto& m : ns->mappings) {+ if (m.chainIndex != chain || m.deviceIndex < 0) continue;+ if (m.deviceIndex == from) m.deviceIndex = to;+ else if (from < to && m.deviceIndex > from && m.deviceIndex <= to) --m.deviceIndex;+ else if (to < from && m.deviceIndex >= to && m.deviceIndex < from) ++m.deviceIndex;+ }commit(ns);return true;}@@ -687,7 +711,16 @@ protected:const float target = m.rangeMin + applyCurve(value, m.curve) * (m.rangeMax - m.rangeMin);if (m.chainIndex < 0 || m.chainIndex >= static_cast<int32_t>(st->chains.size())) continue;auto& c = st->chains[m.chainIndex];- if (m.deviceIndex < 0) {+ if (m.deviceIndex == kPadControls) {+ auto& k = *c.ctl;+ switch (m.paramIndex) {+ case PadVolume: k.gain.store(std::clamp(target, 0.0f, 4.0f), std::memory_order_relaxed); break;+ case PadPan: k.pan.store(std::clamp(target, -1.0f, 1.0f), std::memory_order_relaxed); break;+ case PadTune: k.tune.store(std::clamp(static_cast<int32_t>(std::lround(target)), -48, 48), std::memory_order_relaxed); break;+ case PadDecay: k.decay.store(std::clamp(target, 0.0f, 1.0f), std::memory_order_relaxed); break;+ default: break;+ }+ } else if (m.deviceIndex < 0) {if (c.instrument) c.instrument->pluginParamSet(m.paramIndex, target);} else if (m.deviceIndex < static_cast<int32_t>(c.devices.size())) {if (c.devices[m.deviceIndex]) c.devices[m.deviceIndex]->setParam(m.paramIndex, target);diff --git a/src/native/nota.engine/src/RhythmMachine.h b/src/native/nota.engine/src/RhythmMachine.hindex 836c382d..c2d49513 100644--- a/src/native/nota.engine/src/RhythmMachine.h+++ b/src/native/nota.engine/src/RhythmMachine.h@@ -26,8 +26,16 @@// The 7 per-voice knobs (Tune/Decay/Punch/Tone/Drive/Level/Pan) + 4 globals ride the plugin-// param interface (normalized 0..1) → automation / persist / clone for free. Appended after// them (param order is the persisted layout — append only): per-voice sample Start / Length /-// Reverse, then Glue (a bus compressor on the kit sum). The step patterns are structural-// state (getState/setState blob + the action() UI channel), not params. A step is on/off with+// Reverse, then Glue (a bus compressor on the kit sum), then eight Macros.+//+// Macros: eight knobs over the whole kit (params macro1..macro8, so they automate and learn+// like any other). A mapping drives one target across [min, max] in the target's own units —+// one of the machine's own params (a voice's Decay, Glue …; normalized) or a param of a+// voice's FX device (the device's units) — so one knob can open every snare and clap reverb+// at once. Mappings live in the FX snapshot (they follow their device when the chain is+// edited) and are saved after the kit label, tagged, with the macros' names.+//+// The step patterns are structural state (getState/setState blob + the action() UI channel), not params. A step is on/off with// a velocity (a "quiet" step is just a low one) and an accent flag. The voice FX chains and a// kit label follow the pattern data in the same blob, tagged, so an older reader stops before// them. Header-only, allocation-free on the audio thread. Name & DSP are Nota's own.@@ -58,11 +66,21 @@ public:static constexpr int kPX = 3; // appended per-voice params (sample region)static constexpr int kLegacyParams = kVoices * kPV + 4; // RTH1 blobs carry exactly thesestatic constexpr int kExtra = kLegacyParams; // first appended per-voice param- static constexpr int kNumParams = kExtra + kVoices * kPX + 1; // + Glue+ static constexpr int kNumParamsV2 = kExtra + kVoices * kPX + 1; // + Glue (RTH2 blobs)+ static constexpr int kMacros = 8;+ static constexpr int kNumParams = kNumParamsV2 + kMacros; // + Macro 1..8 (RTH3)enum VP { Tune = 0, Decay, Punch, Tone, Drive, Level, Pan };enum XP { Start = 0, Length, Reverse };- enum GP { Swing = kVoices * kPV, Humanize, Accent, Volume, Glue = kExtra + kVoices * kPX };+ enum GP { Swing = kVoices * kPV, Humanize, Accent, Volume, Glue = kExtra + kVoices * kPX, Macro0 = kNumParamsV2 };++ // A macro mapping. device -1: param is one of the machine's own params (voice = the voice it+ // belongs to, -1 for a global); device ≥ 0: param of that device on the voice's FX chain.+ struct MacroMap {+ int32_t macro = 0, voice = 0, device = -1, param = 0;+ float lo = 0.0f, hi = 1.0f;+ int32_t curve = 0; // 0 Linear, 1 Exp, 2 Log, 3 S-curve (the rack's curves)+ };// scopeRead layout: the playing step (-1 stopped), the current bank, an edit revision that// bumps on every pattern change (so an editor re-reads the blob after an MCP edit), the// sounding-voice count, the glue gain reduction (dB, ≥ 0), then per voice a trigger flash@@ -87,6 +105,7 @@ public:setP(5, Decay, 0.5f); // Open hat — longpn_[Swing].store(0.0f); pn_[Humanize].store(0.0f); pn_[Accent].store(0.7f); pn_[Volume].store(0.8f);pn_[Glue].store(0.0f);+ for (int m = 0; m < kMacros; ++m) pn_[Macro0 + m].store(0.0f);for (auto& p : pendingTrig_) p.store(-1.0f, std::memory_order_relaxed);for (auto& sc : scope_) sc.store(0.0f, std::memory_order_relaxed);scope_[S_Step].store(-1.0f, std::memory_order_relaxed);@@ -125,6 +144,7 @@ public:// "Master › Glue". Ids never change.std::string pluginParamId(int32_t i) const override {if (i < 0 || i >= kNumParams) return {};+ if (i >= Macro0) return "macro" + std::to_string(i - Macro0 + 1);if (i == Glue) return "glue";if (i >= kExtra) { static const char* x[] = {"start","length","reverse"}; int k = i - kExtra; return "v" + std::to_string(k / kPX) + "_" + x[k % kPX]; }if (i >= kVoices * kPV) { static const char* g[] = {"swing","humanize","accent","volume"}; return g[i - kVoices * kPV]; }@@ -133,6 +153,7 @@ public:}std::string pluginParamName(int32_t i) const override {if (i < 0 || i >= kNumParams) return {};+ if (i >= Macro0) return "Macro " + std::to_string(i - Macro0 + 1);if (i == Glue) return "Master Glue";if (i >= kExtra) { static const char* x[] = {"Start","Length","Reverse"}; int k = i - kExtra; return std::string(kVoiceNames[k / kPX]) + " " + x[k % kPX]; }if (i >= kVoices * kPV) { static const char* g[] = {"Perform Swing","Perform Humanize","Perform Accent","Master Volume"}; return g[i - kVoices * kPV]; }@@ -140,7 +161,12 @@ public:return std::string(kVoiceNames[i / kPV]) + " " + pn[i % kPV];}float pluginParamGet(int32_t i) const override { return (i >= 0 && i < kNumParams) ? pn_[i].load(std::memory_order_relaxed) : 0.0f; }- void pluginParamSet(int32_t i, float v) override { if (i >= 0 && i < kNumParams) pn_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed); }+ void pluginParamSet(int32_t i, float v) override {+ if (i < 0 || i >= kNumParams) return;+ v = std::clamp(v, 0.0f, 1.0f);+ pn_[i].store(v, std::memory_order_relaxed);+ if (i >= Macro0) applyMacro(i - Macro0, v);+ }int32_t pluginParamIndexOfId(const std::string& id) const override {for (int32_t i = 0; i < kNumParams; ++i) if (pluginParamId(i) == id) return i;return -1;@@ -208,6 +234,12 @@ public:auto ns = copyFx();if (v < 0 || v >= kVoices || d < 0 || d >= static_cast<int>(ns->chain[v].size())) return false;ns->chain[v].erase(ns->chain[v].begin() + d);+ auto& mv = ns->maps; // a mapping follows its device: the removed one's go, later ones shift+ for (auto it = mv.begin(); it != mv.end();) {+ if (it->voice == v && it->device == d) { it = mv.erase(it); continue; }+ if (it->voice == v && it->device > d) --it->device;+ ++it;+ }commitFx(ns);return true;}@@ -222,6 +254,12 @@ public:auto x = c[from];c.erase(c.begin() + from);c.insert(c.begin() + to, x);+ for (auto& m : ns->maps) {+ if (m.voice != v || m.device < 0) continue;+ if (m.device == from) m.device = to;+ else if (from < to && m.device > from && m.device <= to) --m.device;+ else if (to < from && m.device >= to && m.device < from) ++m.device;+ }commitFx(ns);return true;}@@ -229,8 +267,68 @@ public:auto ns = copyFx();if (v < 0 || v >= kVoices || ns->chain[v].empty()) return;ns->chain[v].clear();+ std::erase_if(ns->maps, [v](const MacroMap& m) { return m.voice == v && m.device >= 0; });+ commitFx(ns);+ }+ // ---- macros (message thread; the audio thread reads the mappings in the FX snapshot) ----+ std::string macroName(int m) const {+ if (m < 0 || m >= kMacros) return {};+ return macroNames_[m].empty() ? "Macro " + std::to_string(m + 1) : macroNames_[m];+ }+ void setMacroName(int m, const std::string& n) { if (m >= 0 && m < kMacros) macroNames_[m] = n.substr(0, 32); }+ // Adds a mapping and applies the macro's current value to it. Returns its index, -1 when the+ // target doesn't exist (a macro can't drive a macro).+ int32_t addMacroMapping(int macro, int voice, int device, int param, float lo, float hi) {+ if (macro < 0 || macro >= kMacros) return -1;+ if (device < 0) { if (param < 0 || param >= Macro0) return -1; }+ else if (!voiceDevice(voice, device) || param < 0 || param >= voiceDevice(voice, device)->paramCount()) return -1;+ auto ns = copyFx();+ ns->maps.push_back({macro, device < 0 ? paramVoice(param) : voice, device, param, lo, hi, 0});+ const int32_t idx = static_cast<int32_t>(ns->maps.size()) - 1;+ commitFx(ns);+ applyMacro(macro, get(Macro0 + macro));+ return idx;+ }+ int32_t macroMappingCount() const { FxState* fx = fxLive_.load(std::memory_order_acquire); return fx ? static_cast<int32_t>(fx->maps.size()) : 0; }+ bool macroMapping(int i, MacroMap& out) const {+ FxState* fx = fxLive_.load(std::memory_order_acquire);+ if (!fx || i < 0 || i >= static_cast<int>(fx->maps.size())) return false;+ out = fx->maps[i];+ return true;+ }+ bool removeMacroMapping(int i) {+ auto ns = copyFx();+ if (i < 0 || i >= static_cast<int>(ns->maps.size())) return false;+ ns->maps.erase(ns->maps.begin() + i);commitFx(ns);+ return true;+ }+ bool setMacroMappingRange(int i, float lo, float hi) {+ auto ns = copyFx();+ if (i < 0 || i >= static_cast<int>(ns->maps.size())) return false;+ ns->maps[i].lo = lo; ns->maps[i].hi = hi;+ const int m = ns->maps[i].macro;+ commitFx(ns);+ applyMacro(m, get(Macro0 + m));+ return true;}+ bool setMacroMappingCurve(int i, int curve) {+ auto ns = copyFx();+ if (i < 0 || i >= static_cast<int>(ns->maps.size())) return false;+ ns->maps[i].curve = std::clamp(curve, 0, 3);+ const int m = ns->maps[i].macro;+ commitFx(ns);+ applyMacro(m, get(Macro0 + m));+ return true;+ }+ // Every mapping and name back to empty (a kit load starts the macros over). Values stay.+ void clearMacros() {+ auto ns = copyFx();+ ns->maps.clear();+ commitFx(ns);+ for (auto& n : macroNames_) n.clear();+ }+// The factory kit the voices came from ("" = none / hand-built) — display metadata only.const std::string& kitName() const { return kit_; }void setKitName(const std::string& k) { kit_ = k.substr(0, 64); }@@ -265,6 +363,17 @@ public:}putU32(b, static_cast<uint32_t>(kit_.size()));b.insert(b.end(), kit_.begin(), kit_.end());+ // Macro mappings + names, tagged "RMC1".+ putU32(b, kMacMagic);+ const int nm = fx ? static_cast<int>(fx->maps.size()) : 0;+ putU32(b, static_cast<uint32_t>(nm));+ for (int i = 0; i < nm; ++i) {+ const auto& m = fx->maps[i];+ putU32(b, (uint32_t)m.macro); putU32(b, (uint32_t)m.voice); putU32(b, (uint32_t)m.device); putU32(b, (uint32_t)m.param);+ uint32_t u; std::memcpy(&u, &m.lo, 4); putU32(b, u); std::memcpy(&u, &m.hi, 4); putU32(b, u);+ putU32(b, (uint32_t)m.curve);+ }+ for (int m = 0; m < kMacros; ++m) { putU32(b, static_cast<uint32_t>(macroNames_[m].size())); b.insert(b.end(), macroNames_[m].begin(), macroNames_[m].end()); }return b;}void setState(const uint8_t* data, int32_t size) override {@@ -274,6 +383,7 @@ public:off = 4;int nParams;if (magic == kMagic) nParams = kNumParams;+ else if (magic == kMagicV2) nParams = kNumParamsV2;else if (magic == kMagicV1) nParams = kLegacyParams;else return; // unknown — keep defaultsrev_.fetch_add(1, std::memory_order_relaxed);@@ -308,10 +418,34 @@ public:}}uint32_t kl = 0;- if (getU32(kl) && kl <= 64 && off + (int)kl <= size) kit.assign(reinterpret_cast<const char*>(data + off), kl);+ if (getU32(kl) && kl <= 64 && off + (int)kl <= size) { kit.assign(reinterpret_cast<const char*>(data + off), kl); off += (int)kl; }+ }+ // Macro mappings + names. Absent before RMC1: no mappings, default names.+ std::string names[kMacros];+ if (getU32(tag) && tag == kMacMagic) {+ uint32_t n = 0;+ if (getU32(n))+ for (uint32_t i = 0; i < n && i < 4096; ++i) {+ uint32_t f[7];+ bool ok = true;+ for (auto& x : f) ok = ok && getU32(x);+ if (!ok) break;+ MacroMap m;+ m.macro = (int32_t)f[0]; m.voice = (int32_t)f[1]; m.device = (int32_t)f[2]; m.param = (int32_t)f[3];+ std::memcpy(&m.lo, &f[4], 4); std::memcpy(&m.hi, &f[5], 4); m.curve = std::clamp((int32_t)f[6], 0, 3);+ const bool target = m.device < 0 ? (m.param >= 0 && m.param < Macro0)+ : (m.voice >= 0 && m.voice < kVoices && m.device < (int)ns->chain[m.voice].size());+ if (m.macro >= 0 && m.macro < kMacros && target && std::isfinite(m.lo) && std::isfinite(m.hi)) ns->maps.push_back(m);+ }+ for (int m = 0; m < kMacros; ++m) {+ uint32_t l = 0;+ if (!getU32(l) || l > 32 || off + (int)l > size) break;+ names[m].assign(reinterpret_cast<const char*>(data + off), l); off += (int)l;+ }}commitFx(ns);kit_ = kit;+ for (int m = 0; m < kMacros; ++m) macroNames_[m] = names[m];}std::shared_ptr<Instrument> clone() const override {auto r = std::make_shared<RhythmMachine>();@@ -336,8 +470,10 @@ public:c->setBypassed(d->bypassed());ns->chain[v].push_back(std::move(c));}+ if (FxState* fx = fxLive_.load(std::memory_order_acquire)) ns->maps = fx->maps;r->commitFx(ns);r->kit_ = kit_;+ for (int m = 0; m < kMacros; ++m) r->macroNames_[m] = macroNames_[m];return r;}@@ -478,12 +614,45 @@ public:private:static constexpr uint32_t kMagicV1 = 0x31485452; // "RTH1" — 60 params- static constexpr uint32_t kMagic = 0x32485452; // "RTH2" — + sample region, Glue+ static constexpr uint32_t kMagicV2 = 0x32485452; // "RTH2" — + sample region, Glue+ static constexpr uint32_t kMagic = 0x33485452; // "RTH3" — + Macro 1..8static constexpr uint32_t kFxMagic = 0x31584652; // "RFX1" — voice FX chains + kit label, after the pattern+ static constexpr uint32_t kMacMagic = 0x31434D52; // "RMC1" — macro mappings + names, after the kit labelstatic constexpr int kChunk = 256; // render chunk = the voice FX's max blockstatic constexpr int kMaxFx = 8; // devices per voice chain- struct FxState { std::vector<std::shared_ptr<Device>> chain[kVoices]; };+ struct FxState { std::vector<std::shared_ptr<Device>> chain[kVoices]; std::vector<MacroMap> maps; };++ // The voice a param belongs to (-1 for the globals).+ static int paramVoice(int p) {+ if (p < kVoices * kPV) return p / kPV;+ if (p >= kExtra && p < Glue) return (p - kExtra) / kPX;+ return -1;+ }+ static float macroCurve(float v, int32_t curve) {+ v = std::clamp(v, 0.0f, 1.0f);+ switch (curve) {+ case 1: return v * v;+ case 2: return std::sqrt(v);+ case 3: return v * v * (3.0f - 2.0f * v);+ default: return v;+ }+ }+ // Push macro m's value to its targets. Any thread (automation plays on the audio thread):+ // it only reads the live snapshot and stores atomics / device params.+ void applyMacro(int m, float value) {+ FxState* fx = fxLive_.load(std::memory_order_acquire);+ if (!fx) return;+ for (const auto& mp : fx->maps) {+ if (mp.macro != m) continue;+ const float t = mp.lo + macroCurve(value, mp.curve) * (mp.hi - mp.lo);+ if (mp.device < 0) {+ if (mp.param >= 0 && mp.param < Macro0) pn_[mp.param].store(std::clamp(t, 0.0f, 1.0f), std::memory_order_relaxed);+ } else if (mp.voice >= 0 && mp.voice < kVoices && mp.device < static_cast<int>(fx->chain[mp.voice].size())) {+ if (auto& d = fx->chain[mp.voice][mp.device]) d->setParam(mp.param, t);+ }+ }+ }std::shared_ptr<FxState> copyFx() const { return fxAuthoring_ ? std::make_shared<FxState>(*fxAuthoring_) : std::make_shared<FxState>(); }// Publish a new FX snapshot. The last few stay alive so a block still reading an older// one never sees it freed (the RackCore scheme).@@ -688,6 +857,7 @@ private:std::vector<std::shared_ptr<FxState>> fxStates_; // recent snapshots kept alivestd::atomic<FxState*> fxLive_{nullptr};std::string kit_; // factory kit label (message thread)+ std::string macroNames_[kMacros]; // custom macro names ("" = "Macro N"; message thread)float mix_[kChunk * 2]; // audio thread: the chunk's sumfloat vbuf_[kVoices][kChunk * 2]; // audio thread: FX voices, pre-chain};diff --git a/src/native/nota.engine/src/nota_engine_track.cpp b/src/native/nota.engine/src/nota_engine_track.cppindex 4e4dbec9..e6217be3 100644--- a/src/native/nota.engine/src/nota_engine_track.cpp+++ b/src/native/nota.engine/src/nota_engine_track.cpp@@ -190,6 +190,27 @@ const char* nota_rhythm_kit_name(const NotaEngine* e, int32_t t) {void nota_rhythm_set_kit_name(NotaEngine* e, int32_t t, const char* name) {if (e) ENG(e)->setRhythmKitName(t, name ? name : "");}+const char* nota_rhythm_macro_name(const NotaEngine* e, int32_t t, int32_t m) {+ static std::string s; s = e ? CENG(e)->rhythmMacroName(t, m) : std::string{}; return s.c_str();+}+void nota_rhythm_set_macro_name(NotaEngine* e, int32_t t, int32_t m, const char* name) {+ if (e) ENG(e)->setRhythmMacroName(t, m, name ? name : "");+}+int32_t nota_rhythm_add_macro_mapping(NotaEngine* e, int32_t t, int32_t m, int32_t v, int32_t d, int32_t p, float lo, float hi) {+ return e ? ENG(e)->rhythmAddMacroMapping(t, m, v, d, p, lo, hi) : -1;+}+int32_t nota_rhythm_macro_mapping_count(const NotaEngine* e, int32_t t) { return e ? CENG(e)->rhythmMacroMappingCount(t) : 0; }+int32_t nota_rhythm_macro_mapping_info(const NotaEngine* e, int32_t t, int32_t i, int32_t* m, int32_t* v, int32_t* d, int32_t* p,+ float* lo, float* hi, int32_t* curve) {+ int32_t a = 0, b = 0, c = -1, pp = 0, cv = 0; float l = 0.0f, h = 1.0f;+ if (!e || !CENG(e)->rhythmMacroMappingInfo(t, i, a, b, c, pp, l, h, cv)) return 0;+ if (m) *m = a; if (v) *v = b; if (d) *d = c; if (p) *p = pp; if (lo) *lo = l; if (hi) *hi = h; if (curve) *curve = cv;+ return 1;+}+int32_t nota_rhythm_remove_macro_mapping(NotaEngine* e, int32_t t, int32_t i) { return (e && ENG(e)->rhythmRemoveMacroMapping(t, i)) ? 1 : 0; }+int32_t nota_rhythm_set_macro_mapping_range(NotaEngine* e, int32_t t, int32_t i, float lo, float hi) { return (e && ENG(e)->rhythmSetMacroMappingRange(t, i, lo, hi)) ? 1 : 0; }+int32_t nota_rhythm_set_macro_mapping_curve(NotaEngine* e, int32_t t, int32_t i, int32_t curve) { return (e && ENG(e)->rhythmSetMacroMappingCurve(t, i, curve)) ? 1 : 0; }+void nota_rhythm_clear_macros(NotaEngine* e, int32_t t) { if (e) ENG(e)->rhythmClearMacros(t); }int32_t nota_track_set_grain_sample(NotaEngine* e, int32_t track_id, const char* path, int32_t root) {if (!e || !path) return 0;return ENG(e)->setTrackGrainSample(track_id, std::string(path), root) ? 1 : 0;diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 4ffed343..303b822a 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -10954,7 +10954,7 @@ Console.WriteLine("-- Nota Rhythm --");Check(re.TrackInstrumentKind(t) == 12, $"instrument kind is 12 ({re.TrackInstrumentKind(t)})");Check(re.DeviceName(t, -1) == "Nota Rhythm", $"name is Nota Rhythm ('{re.DeviceName(t, -1)}')");int pc = re.PluginParamCount(t, -1);- Check(pc == 85, $"param count 85 (got {pc})");+ Check(pc == 93, $"param count 93 — 85 + eight macros (got {pc})");int RIdx(NotaEngine e, int tr, string id) { for (int i = 0; i < e.PluginParamCount(tr, -1); i++) if (e.PluginParamId(tr, -1, i) == id) return i; return -1; }Check(re.PluginParamName(t, -1, RIdx(re, t, "v4_decay")) == "Closed Hat Decay" && re.PluginParamName(t, -1, RIdx(re, t, "swing")) == "Perform Swing"&& re.PluginParamName(t, -1, RIdx(re, t, "glue")) == "Master Glue" && re.PluginParamName(t, -1, RIdx(re, t, "v2_start")) == "Clap Start",@@ -11004,7 +11004,7 @@ Console.WriteLine("-- Nota Rhythm --");var v1 = new List<byte>();v1.AddRange(BitConverter.GetBytes(0x31485452u));v1.AddRange(v2.Skip(4).Take(60 * 4));- v1.AddRange(v2.Skip(4 + 85 * 4));+ v1.AddRange(v2.Skip(4 + 93 * 4));using var old = new NotaEngine();int to = old.AddRhythmTrack();old.InstrumentAction(to, 4, 0, 0); // clear, so the steps must come from the blob@@ -11013,7 +11013,7 @@ Console.WriteLine("-- Nota Rhythm --");Check(Math.Abs(old.PluginParamGet(to, -1, RIdx(old, to, "v0_tune")) - 0.9f) < 0.02f && op.On[0, 0, 0] && op.On[0, 0, 4] && op.On[0, 4, 2]&& Math.Abs(old.PluginParamGet(to, -1, RIdx(old, to, "v0_length")) - 1f) < 1e-4f,"an RTH1 blob (older projects) restores params and steps; new params keep defaults");- var legacy = RhythmModel.Parse(v1.ToArray(), 85);+ var legacy = RhythmModel.Parse(v1.ToArray(), 93);Check(legacy.On[0, 0, 0] && legacy.On[0, 4, 2] && !legacy.On[0, 1, 0], "RhythmModel.Parse reads an RTH1 blob");}@@ -11309,6 +11309,160 @@ Console.WriteLine("-- Kit FX --");for (int i = 0; i < clap.Length / 2; i++) { double l = clap[2 * i], r = clap[2 * i + 1]; side += (l - r) * (l - r); mid += (l + r) * (l + r); }Check(side > mid * 0.005, $"a stereo kit sample plays in stereo on a Rhythm voice (side/mid {side / Math.Max(mid, 1e-12):0.000})");}+// ============ Kit macros: Drum Rack + Rhythm ============+// Every factory kit loads with its own macros, mapped onto pad controls and onto the pads'+// built-in effects; a fresh kit sounds exactly as its recipe (each macro sits on the value its+// targets load with).+Console.WriteLine("-- Kit macros --");+{+ var svc = new DrumKitService();+ static float Lerp(RackMacroMapping m, float v) => m.RangeMin + v * (m.RangeMax - m.RangeMin);++ // ---- Drum Rack ----+ using var e = new NotaEngine();+ int t = svc.CreateTrack(e, "kompakt", out _);+ int Chain(int note) { for (int c = 0; c < e.RackChainCount(t); c++) if (e.RackChainTriggerNote(t, c) == note) return c; return -1; }+ int Param(int c, int d, string name) => Enumerable.Range(0, e.RackChainDeviceParamCount(t, c, d)).First(p => e.RackChainDeviceParamName(t, c, d, p) == name);+ var names = Enumerable.Range(0, 8).Select(m => e.RackMacroName(t, m)).ToArray();+ Check(names.Take(6).SequenceEqual(new[] { "Tune", "Decay", "Hats", "Drive", "Room", "Echo" }) && names[7] == "Macro 8",+ $"a Drum Rack kit loads its macros ({string.Join(", ", names)})");+ float RackTarget(RackMacroMapping m) => m.DeviceIndex switch+ {+ RackMacroMapping.PadControls => m.ParamIndex == RackMacroMapping.PadTune ? e.RackChainTune(t, m.Chain) : e.RackChainDecay(t, m.Chain),+ _ => e.RackChainDeviceParamGet(t, m.Chain, m.DeviceIndex, m.ParamIndex),+ };+ var maps = Enumerable.Range(0, e.RackMappingCount(t)).Select(i => { e.RackTryGetMapping(t, i, out var m); return m; }).ToList();+ Check(maps.Count > 30 && maps.All(m => Math.Abs(RackTarget(m) - Lerp(m, e.RackMacroGet(t, m.Macro))) < 1e-3f),+ $"the kit's macros sit on the values the pads load with ({maps.Count} mappings)");+ Check(maps.Any(m => m.Macro == 4 && m.Chain == Chain(38) && m.DeviceIndex == 0) && maps.Any(m => m.Macro == 3 && m.Chain == Chain(36) && m.DeviceIndex == 0),+ "the Room and Drive macros map onto the pads' own Reverb and Forge");++ int sn = Chain(38), dw = Param(sn, 0, "Dry/Wet");+ float wet0 = e.RackChainDeviceParamGet(t, sn, 0, dw);+ e.RackMacroSet(t, 4, 1f);+ Check(Math.Abs(e.RackChainDeviceParamGet(t, sn, 0, dw) - 2 * wet0) < 1e-3f, $"turning Room opens the snare reverb ({wet0:0.00} → {e.RackChainDeviceParamGet(t, sn, 0, dw):0.00})");+ e.RackMacroSet(t, 1, 0f);+ e.RackMacroSet(t, 0, 1f);+ Check(e.RackChainDecay(t, Chain(36)) < 0.3f && e.RackChainDecay(t, Chain(42)) > 0.99f && e.RackChainTune(t, Chain(36)) == 12,+ "Decay gates the drums but not the hats; Tune moves the pads' pitch");++ // A mapping follows its device: one put in front shifts it, removing it drops the mapping.+ e.RackAddChainDevice(t, sn, 1);+ e.RackMoveChainDevice(t, sn, 1, 0);+ bool Follows(int dev) => Enumerable.Range(0, e.RackMappingCount(t)).Any(i => e.RackTryGetMapping(t, i, out var m) && m.Macro == 4 && m.Chain == sn && m.DeviceIndex == dev);+ Check(Follows(1) && !Follows(0), "a macro mapping follows its device when the chain is reordered");+ e.RackRemoveChainDevice(t, sn, 1);+ Check(!Follows(1) && !Follows(0), "removing a device drops the macro mappings onto it");++ // Save / copy: the mappings (pad controls too) ride the rack.+ int n0 = e.RackMappingCount(t);+ int dup = e.DuplicateTrack(t);+ Check(dup > 0 && e.RackMappingCount(dup) == n0 && e.RackMacroName(dup, 4) == "Room", "duplicating a Drum Rack copies its macros and mappings");+ e.RackMacroSet(dup, 1, 1f);+ Check(e.RackChainDecay(dup, Chain(36)) > 0.99f && e.RackChainDecay(t, Chain(36)) < 0.3f, "the copy's macros drive the copy's pads");++ // Another kit replaces them. Aether's snare and clap carry their room in the sample, so no+ // reverb and no Room macro; Neon has an 808.+ svc.LoadInto(e, t, "aether", out _);+ Check(e.RackMacroName(t, 4) == "Macro 5" && e.RackMacroName(t, 1) == "Decay" && Enumerable.Range(0, e.RackMappingCount(t)).All(i => e.RackTryGetMapping(t, i, out var m) && m.Chain < e.RackChainCount(t)),+ "loading another kit replaces the macros");+ int neon = svc.CreateTrack(e, "neon", out _);+ Check(e.RackMacroName(neon, 6) == "808", "a kit with an 808 gets a macro for it");+ bool allKits = true;+ foreach (var k in svc.All())+ {+ int kt = svc.CreateTrack(e, k.Id, out _);+ int mc = e.RackMappingCount(kt);+ for (int i = 0; i < mc && allKits; i++)+ {+ e.RackTryGetMapping(kt, i, out var m);+ float cur = m.DeviceIndex == RackMacroMapping.PadControls+ ? (m.ParamIndex == RackMacroMapping.PadTune ? e.RackChainTune(kt, m.Chain) : e.RackChainDecay(kt, m.Chain))+ : e.RackChainDeviceParamGet(kt, m.Chain, m.DeviceIndex, m.ParamIndex);+ if (Math.Abs(cur - Lerp(m, e.RackMacroGet(kt, m.Macro))) > 1e-3f || !float.IsFinite(m.RangeMax)) { allKits = false; Console.WriteLine($" {k.Id}: macro {m.Macro} mapping {i} off"); }+ }+ if (mc < 10) { allKits = false; Console.WriteLine($" {k.Id}: only {mc} mappings"); }+ e.RemoveTrack(kt);+ }+ Check(allKits, "every factory kit loads macros that leave its sound as the recipe made it");++ // ---- Rhythm ----+ using var re = new NotaEngine();+ int rt = svc.CreateRhythmTrack(re, "kompakt", out _);+ var ids = Enumerable.Range(0, re.PluginParamCount(rt, -1)).ToDictionary(i => re.PluginParamId(rt, -1, i), i => i);+ float G(string id) => re.PluginParamGet(rt, -1, ids[id]);+ void S(string id, float v) => re.PluginParamSet(rt, -1, ids[id], v);+ var rnames = Enumerable.Range(0, 8).Select(m => re.RhythmMacroName(rt, m)).ToArray();+ Check(ids.ContainsKey("macro1") && ids.ContainsKey("macro8") && rnames.Take(6).SequenceEqual(names.Take(6)),+ $"a Rhythm kit loads the same macros ({string.Join(", ", rnames)})");+ float RTarget(NotaEngine x, int tr, RackMacroMapping m) => m.DeviceIndex < 0 ? x.PluginParamGet(tr, -1, m.ParamIndex) : x.RhythmVoiceDeviceParamGet(tr, m.Chain, m.DeviceIndex, m.ParamIndex);+ var rmaps = Enumerable.Range(0, re.RhythmMacroMappingCount(rt)).Select(i => { re.RhythmTryGetMacroMapping(rt, i, out var m, out _); return m; }).ToList();+ Check(rmaps.Count >= 20 && rmaps.All(m => Math.Abs(RTarget(re, rt, m) - Lerp(m, G($"macro{m.Macro + 1}"))) < 1e-3f)+ && rmaps.Any(m => m.Macro == 4 && m.Chain == 1 && m.DeviceIndex == 0),+ $"the Rhythm's macros sit on its voices' values, and reach the voices' effects ({rmaps.Count} mappings)");+ int rdw = Enumerable.Range(0, re.RhythmVoiceDeviceParamCount(rt, 1, 0)).First(p => re.RhythmVoiceDeviceParamName(rt, 1, 0, p) == "Dry/Wet");+ float rwet0 = re.RhythmVoiceDeviceParamGet(rt, 1, 0, rdw);+ S("macro5", 1f); S("macro2", 0f);+ Check(Math.Abs(re.RhythmVoiceDeviceParamGet(rt, 1, 0, rdw) - 2 * rwet0) < 1e-3f && G("v0_decay") < 0.3f && G("v4_decay") > 0.99f,+ "turning a Rhythm macro moves the voice FX and voice params");++ // Heard: Decay at the bottom shortens the kick.+ float[] Kick(NotaEngine x, int tr)+ {+ x.InstrumentAction(tr, RhythmModel.A_ClearBank, 0, 0);+ x.InstrumentAction(tr, RhythmModel.A_ToggleStep, 0, 0);+ x.InstrumentAction(tr, RhythmModel.A_SetVel, 0, 1f);+ x.Seek(0); x.Play();+ var buf = new float[44100 * 2]; var blk = new float[512 * 2];+ for (int done = 0; done < 44100; done += 512) { x.RenderOffline(blk, 512); Array.Copy(blk, 0, buf, done * 2, Math.Min(512, 44100 - done) * 2); }+ x.StopTransport();+ return buf;+ }+ static double Tail(float[] b) { double q = 0; for (int i = 44100 / 4 * 2; i < b.Length; i++) q += b[i] * b[i]; return q; }+ double shortTail = Tail(Kick(re, rt));+ S("macro2", 1f);+ double longTail = Tail(Kick(re, rt));+ Check(longTail > shortTail * 4 && double.IsFinite(longTail), $"the Decay macro is heard: the kick's tail {10 * Math.Log10(longTail / Math.Max(shortTail, 1e-12)):0} dB longer from bottom to top");++ // Save / load and copy.+ re.RhythmSetMacroName(rt, 7, "Wash");+ re.RhythmAddMacroMapping(rt, 7, -1, -1, ids["glue"], 0f, 1f);+ S("macro8", 0.25f);+ var blob = re.GetPluginState(rt, -1);+ using (var le = new NotaEngine())+ {+ int lt = le.AddRhythmTrack();+ le.SetPluginState(lt, -1, blob);+ Check(le.RhythmMacroMappingCount(lt) == re.RhythmMacroMappingCount(rt) && le.RhythmMacroName(lt, 7) == "Wash" && le.RhythmMacroName(lt, 4) == "Room"+ && Math.Abs(le.PluginParamGet(lt, -1, ids["macro8"]) - 0.25f) < 1e-4f,+ "the Rhythm's macros, mappings and names restore from the state blob");+ le.PluginParamSet(lt, -1, ids["macro5"], 0f);+ Check(le.RhythmVoiceDeviceParamGet(lt, 1, 0, rdw) < 1e-4f, "a restored macro drives the restored voice FX");+ // A blob from before the macros (RTH2): no macro floats, no macro section — it loads as it was.+ int nV2 = RhythmModel.ParamsV2;+ var v2 = new List<byte>(BitConverter.GetBytes(0x32485452u));+ v2.AddRange(blob.Skip(4).Take(nV2 * 4));+ v2.AddRange(blob.Skip(4 + (nV2 + 8) * 4));+ int macTag = Enumerable.Range(0, v2.Count - 3).Last(i => v2[i] == (byte)'R' && v2[i + 1] == (byte)'M' && v2[i + 2] == (byte)'C' && v2[i + 3] == (byte)'1');+ int lt2 = le.AddRhythmTrack();+ le.SetPluginState(lt2, -1, v2.Take(macTag).ToArray());+ var p2 = RhythmModel.Parse(le.GetPluginState(lt2, -1), le.PluginParamCount(lt2, -1));+ Check(le.RhythmMacroMappingCount(lt2) == 0 && le.RhythmVoiceDeviceCount(lt2, 1) == 1 && p2.On[0, 0, 0]+ && Math.Abs(le.PluginParamGet(lt2, -1, ids["glue"]) - re.PluginParamGet(rt, -1, ids["glue"])) < 1e-4f,+ "an RTH2 Rhythm blob (before macros) loads its params, pattern and FX");+ }+ int rdup = re.DuplicateTrack(rt);+ Check(rdup > 0 && re.RhythmMacroMappingCount(rdup) == re.RhythmMacroMappingCount(rt) && re.RhythmMacroName(rdup, 7) == "Wash",+ "duplicating a Rhythm copies its macros");+ re.RhythmRemoveVoiceDevice(rt, 1, 0);+ bool anyOnRemoved = Enumerable.Range(0, re.RhythmMacroMappingCount(rt)).Any(i => re.RhythmTryGetMacroMapping(rt, i, out var m, out _) && m.Chain == 1 && m.DeviceIndex >= 0);+ Check(!anyOnRemoved && re.RhythmMacroMappingCount(rdup) > re.RhythmMacroMappingCount(rt), "removing a voice effect drops its macro mappings (the copy keeps its own)");+ Check(re.RhythmAddMacroMapping(rt, 0, -1, -1, ids["macro2"], 0f, 1f) < 0, "a macro can't be mapped onto a macro");+ // Yard (dub): tape on the kick and a dub echo — the knobs say so.+ svc.LoadInto(re, rt, "yard", out _);+ Check(re.RhythmMacroName(rt, 3) == "Tape" && re.RhythmMacroName(rt, 5) == "Dub" && re.RhythmMacroName(rt, 7) == "Macro 8",+ $"loading a kit into a Rhythm replaces its macros ({string.Join(", ", Enumerable.Range(0, 8).Select(m => re.RhythmMacroName(rt, m)))})");+}// ============ track groups (submix) ======================================Console.WriteLine("-- track groups --");{