Просмотр исходного кода

Layer channel: children, random / sequential / crossfade, key regions, split, FL import

FL's Layer generator (REA_rodada164a): a channel that plays its children. Notes through a Layer are copied to the
children inside the chunk (sample-accurate) with the Layer's volume, pan and pitch; Random picks one child per note,
Sequential plays them in turn, Crossfade blends neighbours with the Fade knob. Every channel gets a key region (a
ruler over the root-note keyboard in Miscellaneous settings) and notes outside it are skipped. Layering menu: split
the children one key each from the root, reset, group, delete. .flp import of Layer channels (children 0x5E, flags
0x90). Project file keeps keyRegion and layer settings.
Ka1-S 1 месяц назад
Родитель
Сommit
8a0f60eae0

+ 2 - 0
CMakeLists.txt

@@ -141,6 +141,7 @@ add_library(lynx_core STATIC
     src/core/FormulaController.cpp
     src/core/VoiceShift.cpp
     src/core/NativeEngines.cpp
+    src/core/Layer.cpp
     src/core/FabFilterStates.cpp
     src/core/FlResampler.cpp
     src/core/FlKeys.cpp
@@ -308,6 +309,7 @@ if(LYNX_BUILD_APP)
         src/ui/ControllerEditors.cpp
         src/ui/NewtoneEditor.cpp
         src/ui/ChannelSettings.cpp
+        src/ui/LayerEditor.cpp
         src/ui/SoundFontEditor.cpp
         src/ui/BrowserComponent.cpp
         src/ui/Theme.cpp

+ 30 - 0
resources/i18n/pt-BR.txt

@@ -4845,3 +4845,33 @@ countries: br
 "Sample browser (separate window)" = "Browser de samples (janela separada)"
 "Sample browser" = "Browser de samples"
 "Open in the file manager" = "Abrir no gerenciador de arquivos"
+
+# round 164a: Layer channel
+"Layer" = "Layer"
+"Key region: {0} to {1} (drag to set, double-click for the whole keyboard)" = "Região de teclas: {0} a {1} (arraste para definir, clique duplo para o teclado inteiro)"
+"Set children" = "Definir filhos"
+"The channels selected in the Channel Rack become this Layer's children (select the ones to keep and press again to remove one)" = "Os canais selecionados no Channel Rack viram filhos deste Layer (selecione os que ficam e clique de novo para remover um)"
+"Show children" = "Mostrar filhos"
+"Selects this Layer's children in the Channel Rack" = "Seleciona os filhos deste Layer no Channel Rack"
+"Layering" = "Camadas"
+"Split, reset, group or delete the children" = "Dividir, redefinir, agrupar ou excluir os filhos"
+"Random: each note plays one child picked at random (varied hits); off = every child plays" = "Aleatório: cada nota toca um filho sorteado (batidas variadas); desligado = todos os filhos tocam"
+"Sequential" = "Sequencial"
+"Sequential: the children play in turn, one per note (round robin)" = "Sequencial: os filhos tocam em revezamento, um por nota (round robin)"
+"Crossfade" = "Crossfade"
+"Crossfade: the Fade knob moves from the first child to the last, blending neighbours" = "Crossfade: o knob Fade vai do primeiro filho ao último, misturando os vizinhos"
+"Layer - Fade (crossfade position)" = "Layer - Fade (posição do crossfade)"
+"Fade" = "Fade"
+"Makes no sound: every note it gets plays its children" = "Não faz som: cada nota que recebe toca os filhos"
+"Children" = "Filhos"
+"No children yet: select channels in the Channel Rack, then press Set children." = "Ainda sem filhos: selecione canais no Channel Rack e clique em Definir filhos."
+"all keys" = "todas as teclas"
+"Remove from this Layer" = "Remover deste Layer"
+"Whole keyboard for this child" = "Teclado inteiro para este filho"
+"child {0}" = "filho {0}"
+"Split children (one key each, from the root key)" = "Dividir filhos (uma tecla cada, a partir da nota raiz)"
+"Reset children (whole keyboard, root on C5)" = "Redefinir filhos (teclado inteiro, raiz em C5)"
+"Group children..." = "Agrupar filhos..."
+"Delete children (removes the channels)" = "Excluir filhos (remove os canais)"
+"Delete children" = "Excluir filhos"
+"Delete the {0} child channels of this Layer from the project?" = "Excluir do projeto os {0} canais filhos deste Layer?"

+ 2 - 0
scripts/build-local.sh

@@ -67,6 +67,8 @@ CORE="$CORE src/core/MidiControls.cpp src/core/FormulaController.cpp"
 CORE="$CORE src/core/VoiceShift.cpp"
 # FL engines usable in native projects (round 142, issue #5)
 CORE="$CORE src/core/NativeEngines.cpp"
+# FL's Layer channel and the round 164 controllers
+CORE="$CORE src/core/Layer.cpp"
 # crash / freeze reports: consent, anonymiser, report JSON, GitHub issue URL (round 159)
 CORE="$CORE src/core/CrashReport.cpp"
 # WavPack decoder (C)

+ 1 - 0
scripts/build-windows-zig.sh

@@ -128,6 +128,7 @@ APP_SOURCES+=(src/core/MidiControls.cpp src/core/FormulaController.cpp src/ui/Co
 APP_SOURCES+=(src/core/VoiceShift.cpp)
 # FL engines usable in native projects (round 142, issue #5)
 APP_SOURCES+=(src/core/NativeEngines.cpp src/ui/NewtoneEditor.cpp)
+APP_SOURCES+=(src/core/Layer.cpp src/ui/LayerEditor.cpp) # FL's Layer channel (round 164)
 # FL's DirectWave (REA round 72)
 APP_SOURCES+=(src/core/DirectWave.cpp)
 # Ogg Vorbis decoding as FL does (REA round 77)

+ 24 - 0
src/Main.cpp

@@ -44,6 +44,7 @@
 #include "core/FlSynths.h"
 #include "ui/Dialogs.h"
 #include "core/RackOps.h"
+#include "core/Layer.h"
 #include "ui/ExportDialog.h"
 #include "ui/I18n.h"
 #include "ui/MainComponent.h"
@@ -4416,6 +4417,27 @@ private:
         settings.port = 1;
         lynx::midictl::writeMidiOut (out.pluginState, settings);
         song.channels.push_back (out);
+        // a Layer (round 164) over three synths split across the keyboard, crossfading
+        for (const auto* name : { "Bass", "Pad", "Lead" })
+        {
+            lynx::ChannelDef c;
+            c.name = name;
+            c.instrument = lynx::InstrumentKind::synth;
+            song.channels.push_back (c);
+        }
+        {
+            lynx::ChannelDef layer;
+            layer.name = "Layer";
+            layer.instrument = lynx::InstrumentKind::layer;
+            song.channels.push_back (layer);
+            const auto self = (int) song.channels.size() - 1;
+            lynx::layer::setChildren (song, self, { 2, 3, 4 });
+            song.channels[2].keyLow = 0, song.channels[2].keyHigh = 47;
+            song.channels[3].keyLow = 36, song.channels[3].keyHigh = 83;
+            song.channels[4].keyLow = 72, song.channels[4].keyHigh = 127;
+            song.channels[(std::size_t) self].layer.crossfade = true;
+            song.channels[(std::size_t) self].layer.fade = 0.35f;
+        }
         song.patterns.emplace_back();
         offline.setSong (std::move (song));
         offline.dispatchPendingMessages();
@@ -4426,6 +4448,8 @@ private:
         };
         shoot (lynx::makeChannelSettingsPanel (offline, 0), "-envelope-controller.png");
         shoot (lynx::makeChannelSettingsPanel (offline, 1), "-midi-out.png");
+        shoot (lynx::makeChannelSettingsPanel (offline, 5), "-layer.png");
+        shoot (lynx::makeChannelSettingsPanel (offline, 3), "-layer-child.png");
         // the Envelope Controller's pages (issue #7): one PNG per part of the dropdown
         if (auto ec = lynx::makeEnvelopeControllerEditor (offline, 0))
             for (int part = 0; part < 7; ++part)

+ 41 - 0
src/core/FlpImport.cpp

@@ -75,6 +75,13 @@ std::string lowercase (std::string s)
 }
 } // namespace
 
+void applyFlLayerFlags (int flags, LayerSettings& layer)
+{
+    // REA_rodada164a §1: bit 0 Random, bit 3 Crossfade
+    layer.random = (flags & 1) != 0;
+    layer.crossfade = (flags & 8) != 0;
+}
+
 InstrumentKind guessInstrument (const std::string& channelName, flp::ChannelType type)
 {
     const auto name = lowercase (channelName);
@@ -513,6 +520,20 @@ void splitDrumChannel (Song& song, int channel, const std::vector<DrumPad>& pads
             c.channel = c.channel >= 0 ? shift (c.channel) : c.channel;
     });
 
+    // Layer children (round 164): shifted; a Layer of the kit plays every pad
+    for (auto& l : song.channels)
+    {
+        std::vector<int> kids;
+        for (const auto k : l.layer.children)
+        {
+            kids.push_back (shift (k));
+            if (k == channel)
+                for (int i = 1; i <= inserted; ++i)
+                    kids.push_back (channel + i);
+        }
+        l.layer.children = std::move (kids);
+    }
+
     song.forEachTarget ([&] (AutomationTarget& t) {
         if ((t.kind == AutomationTargetKind::channelVolume || t.kind == AutomationTargetKind::channelPan
              || t.kind == AutomationTargetKind::channelParam) && t.index >= 0)
@@ -779,6 +800,13 @@ Song importFlp (const flp::Project& input, const FlpImportOptions& options)
         def.name = c.name.empty() ? "Channel " + std::to_string (c.index + 1) : c.name;
         sampleUser = (c.type == flp::ChannelType::audioClip ? "Audio clip: " : "") + def.name;
         def.instrument = guessInstrument (def.name, c.type);
+        // FL's Layer channel (REA_rodada164a §1): its children (FL's channel indices, mapped below) and options
+        if (c.type == flp::ChannelType::layer)
+        {
+            def.instrument = InstrumentKind::layer;
+            def.layer.children = c.layerChildren;
+            applyFlLayerFlags (c.layerFlags, def.layer);
+        }
 
         // FL synthesizer that becomes the internal synth: a preset matching the name (in FLEX, the name
         // of the preset chosen in the plugin says more than the channel's)
@@ -1849,6 +1877,19 @@ Song importFlp (const flp::Project& input, const FlpImportOptions& options)
         song.channels.push_back (std::move (def));
     }
 
+    // Layer children: FL's channel indices → LYNX's (children that did not become channels are dropped)
+    for (auto& def : song.channels)
+        if (def.instrument == InstrumentKind::layer)
+        {
+            std::vector<int> mapped;
+            for (const auto k : def.layer.children)
+                if (const auto found = channelMap.find (k); found != channelMap.end())
+                    mapped.push_back (found->second);
+            def.layer.children = std::move (mapped);
+            if (options.report != nullptr)
+                ++options.report->converted["Layer"];
+        }
+
     // Mixer: names, mute/solo, routing and levels from the .flp; enough inserts for all
     // routes (minimum 16, like a new project). FL's extra tracks (500/501) are left out.
     int highestTrack = 16;

+ 2 - 0
src/core/FlpImport.h

@@ -64,6 +64,8 @@ struct FlpImportOptions
 // by name. Patterns are rescaled to our PPQ. Plugins not yet.
 Song importFlp (const flp::Project& project, const FlpImportOptions& options = {});
 
+// FL Layer channel options (.flp 0x90, REA_rodada164a §1) into LYNX's Layer settings
+void applyFlLayerFlags (int flags, LayerSettings& layer);
 InstrumentKind guessInstrument (const std::string& channelName, flp::ChannelType type);
 
 // Internal synth oscillators from the 3x Osc state (0xD5), versions 10 to 14

+ 2 - 1
src/core/Instruments.cpp

@@ -230,6 +230,7 @@ private:
             case InstrumentKind::plugin:
             case InstrumentKind::controller:
             case InstrumentKind::midiOut:
+            case InstrumentKind::layer:
             case InstrumentKind::patcher:
             case InstrumentKind::sakura:
             case InstrumentKind::drumpad:
@@ -2829,7 +2830,7 @@ std::unique_ptr<Instrument> makeInstrument (InstrumentKind kind, std::shared_ptr
 {
     if (kind == InstrumentKind::controller)
         return std::make_unique<ControllerInstrument>();
-    if (kind == InstrumentKind::midiOut)
+    if (kind == InstrumentKind::midiOut || kind == InstrumentKind::layer) // (a Layer's notes go to its children)
         return std::make_unique<MidiOutInstrument>();
 
     if (kind == InstrumentKind::sampler || kind == InstrumentKind::audioClip)

+ 160 - 0
src/core/Layer.cpp

@@ -0,0 +1,160 @@
+#include "core/Layer.h"
+
+#include <algorithm>
+#include <cmath>
+
+namespace lynx::layer
+{
+namespace
+{
+bool isChild (const std::vector<ChannelDef>& channels, int layer, int c) noexcept
+{
+    return c >= 0 && c < (int) channels.size() && c != layer && channels[(std::size_t) c].instrument != InstrumentKind::layer;
+}
+} // namespace
+
+std::vector<int> validChildren (const Song& song, int layer)
+{
+    std::vector<int> out;
+    if (layer < 0 || layer >= (int) song.channels.size())
+        return out;
+    for (const auto c : song.channels[(std::size_t) layer].layer.children)
+        if (isChild (song.channels, layer, c) && std::find (out.begin(), out.end(), c) == out.end())
+            out.push_back (c);
+    return out;
+}
+
+float levelGain (const ChannelDef& layer) noexcept
+{
+    const auto reference = channelGain (0.78f);
+    return reference > 0.0f ? channelGain (layer.volume) / reference : 1.0f;
+}
+
+float crossfadeGain (int index, int count, float fade) noexcept
+{
+    if (count <= 1)
+        return 1.0f;
+    const auto p = (double) std::clamp (fade, 0.0f, 1.0f) * (double) (count - 1);
+    const auto d = std::abs (p - (double) index);
+    if (d >= 1.0)
+        return 0.0f;
+    return (float) std::cos (d * 1.5707963267948966); // equal power between the two neighbours
+}
+
+int pick (const ChannelDef& layer, const std::vector<ChannelDef>& channels, int key, std::uint32_t& random, int& turn, Pick* out, int max) noexcept
+{
+    const auto& kids = layer.layer.children;
+    const auto count = (int) kids.size();
+    if (count == 0 || max <= 0)
+        return 0;
+    const auto self = (int) (&layer - channels.data()); // (the Layer lives in `channels`)
+    const auto takes = [&] (int k) {
+        const auto c = kids[(std::size_t) k];
+        return isChild (channels, self, c) && channels[(std::size_t) c].inKeyRegion (key);
+    };
+    const auto gainOf = [&] (int k) { return layer.layer.crossfade ? crossfadeGain (k, count, layer.layer.fade) : 1.0f; };
+
+    if (layer.layer.random || layer.layer.sequential)
+    {
+        int candidates = 0;
+        for (int k = 0; k < count; ++k)
+            candidates += takes (k) ? 1 : 0;
+        if (candidates == 0)
+            return 0;
+        int chosen = 0;
+        if (layer.layer.random)
+        {
+            random = random * 1664525u + 1013904223u;
+            chosen = (int) ((std::uint64_t) (random >> 8) * (std::uint64_t) candidates >> 24);
+        }
+        else
+        {
+            chosen = ((turn % candidates) + candidates) % candidates;
+            turn = (chosen + 1) % candidates;
+        }
+        for (int k = 0; k < count; ++k)
+            if (takes (k) && chosen-- == 0)
+            {
+                out[0] = { kids[(std::size_t) k], gainOf (k) };
+                return out[0].gain > 0.0f ? 1 : 0;
+            }
+        return 0;
+    }
+
+    int n = 0;
+    for (int k = 0; k < count && n < max; ++k)
+        if (takes (k))
+            if (const auto g = gainOf (k); g > 0.0f)
+                out[n++] = { kids[(std::size_t) k], g };
+    return n;
+}
+
+void setChildren (Song& song, int layer, std::vector<int> selected)
+{
+    if (layer < 0 || layer >= (int) song.channels.size())
+        return;
+    std::sort (selected.begin(), selected.end());
+    selected.erase (std::unique (selected.begin(), selected.end()), selected.end());
+    selected.erase (std::remove_if (selected.begin(), selected.end(), [&] (int c) { return ! isChild (song.channels, layer, c); }), selected.end());
+    song.channels[(std::size_t) layer].layer.children = std::move (selected);
+}
+
+void setRootNote (ChannelDef& d, int key)
+{
+    key = std::clamp (key, 0, 127);
+    if (d.instrument == InstrumentKind::sampler)
+    {
+        // the sample plays at its own pitch on the root: the pitch moves by the root's change (within ±24)
+        const auto pitch = std::clamp (d.sampler.pitch + (float) (d.misc.rootNote - key), -24.0f, 24.0f);
+        const auto moved = (int) std::lround (pitch - d.sampler.pitch);
+        d.sampler.pitch = pitch;
+        d.misc.rootNote = std::clamp (d.misc.rootNote - moved, 0, 127);
+    }
+    else
+        d.misc.rootNote = key;
+}
+
+void splitChildren (Song& song, int layer)
+{
+    if (layer < 0 || layer >= (int) song.channels.size())
+        return;
+    const auto root = song.channels[(std::size_t) layer].misc.rootNote;
+    const auto kids = validChildren (song, layer);
+    for (std::size_t k = 0; k < kids.size(); ++k)
+    {
+        auto& c = song.channels[(std::size_t) kids[k]];
+        const auto key = std::clamp (root + (int) k, 0, 127);
+        c.keyLow = c.keyHigh = key;
+        setRootNote (c, key);
+        // instruments that are not samplers sound their own pitch on their key through Add to key
+        if (c.instrument != InstrumentKind::sampler && c.instrument != InstrumentKind::audioClip)
+            c.misc.addToKey = true;
+    }
+}
+
+void resetChildren (Song& song, int layer)
+{
+    for (const auto k : validChildren (song, layer))
+    {
+        auto& c = song.channels[(std::size_t) k];
+        c.keyLow = 0;
+        c.keyHigh = 127;
+        setRootNote (c, 60);
+        if (c.instrument != InstrumentKind::sampler && c.instrument != InstrumentKind::audioClip)
+            c.misc.addToKey = false;
+    }
+}
+
+std::vector<int> parentsOf (const Song& song, int channel)
+{
+    std::vector<int> out;
+    for (int l = 0; l < (int) song.channels.size(); ++l)
+        if (song.channels[(std::size_t) l].instrument == InstrumentKind::layer)
+        {
+            const auto& kids = song.channels[(std::size_t) l].layer.children;
+            if (std::find (kids.begin(), kids.end(), channel) != kids.end())
+                out.push_back (l);
+        }
+    return out;
+}
+} // namespace lynx::layer

+ 58 - 0
src/core/Layer.h

@@ -0,0 +1,58 @@
+#pragma once
+
+// FL's Layer channel (docs/analise/REA_rodada164a.md §1; FL's manual "Layer channel settings"): a channel that makes no
+// sound and plays its children channels with every note it gets. Clean-room: our own code from FL's documented and
+// observed behaviour.
+//
+//  - every child plays each note (Random off, Sequential off); Random: one child at random per note; Sequential:
+//    the children in turn (round robin);
+//  - Crossfade: the Fade knob moves through the children top to bottom (child 1, 1+2 blend, child 2…);
+//  - the Layer's VOL / PAN / PITCH apply to the notes it plays (a child played from its own notes is not affected);
+//  - a child plays only the notes inside its key region (ChannelDef::keyLow / keyHigh, any channel); "Split children"
+//    gives each child one key from the Layer's root key up, with its root on that key.
+
+#include <cstdint>
+#include <vector>
+
+#include "core/Song.h"
+
+namespace lynx::layer
+{
+// A child a note plays and the note's level factor for it.
+struct Pick
+{
+    int child = 0;
+    float gain = 1.0f;
+};
+
+// The children (valid channel indices that are not Layers themselves) of channel `layer`.
+std::vector<int> validChildren (const Song& song, int layer);
+
+// The level factor of the Layer's VOL knob for its notes: 1 at FL's default channel volume (0.78), the channel volume
+// curve relative to it otherwise.
+float levelGain (const ChannelDef& layer) noexcept;
+
+// Crossfade: the gain of child `index` of `count` at Fade `fade` (0..1). Position p = fade × (count − 1); a child
+// sounds fully at its own position and fades out linearly towards its neighbours (equal-power blend between them).
+float crossfadeGain (int index, int count, float fade) noexcept;
+
+// Picks the children a note-on of `key` plays (at most `max`, into `out`). `random` is a 32-bit LCG state; `turn` the
+// Sequential counter of this Layer (both advanced). Children whose key region excludes `key` are skipped (a Random /
+// Sequential pick only chooses among the children that take the key). Returns how many. Audio thread: no allocation.
+int pick (const ChannelDef& layer, const std::vector<ChannelDef>& channels, int key, std::uint32_t& random, int& turn, Pick* out, int max) noexcept;
+
+// "Set children": the selected channels (sorted; the Layer itself and other Layers left out) become its children.
+void setChildren (Song& song, int layer, std::vector<int> selected);
+// "Split children": child k plays only key (root + k) and its root note moves there (a sampler's pitch follows so the
+// sample keeps sounding at its own pitch on its key). "Reset children": every child back to the whole keyboard and
+// its root on C5.
+void splitChildren (Song& song, int layer);
+void resetChildren (Song& song, int layer);
+
+// Moves a channel's root note to `key` the way the Root note keyboard does: a sampler's pitch moves with it (within
+// ±24 semitones) so the sample keeps its pitch on the root; other instruments just store it.
+void setRootNote (ChannelDef& channel, int key);
+
+// The Layers whose children include `channel`.
+std::vector<int> parentsOf (const Song& song, int channel);
+} // namespace lynx::layer

+ 10 - 0
src/core/RackOps.cpp

@@ -395,6 +395,12 @@ std::vector<int> unusedChannels (const Song& song)
     for (const auto& a : song.automations)
         mark (a.source.channel);
 
+    // a used Layer's children play its notes (round 164)
+    for (std::size_t c = 0; c < song.channels.size(); ++c)
+        if (used[c] && song.channels[c].instrument == InstrumentKind::layer)
+            for (const auto k : song.channels[c].layer.children)
+                mark (k);
+
     std::vector<int> out;
     for (int i = 0; i < (int) used.size(); ++i)
         if (! used[(std::size_t) i])
@@ -507,6 +513,10 @@ void permuteChannels (Song& song, const std::vector<int>& newOrder)
     for (auto& a : song.automations)
         if (a.source.channel >= 0)
             a.source.channel = map (a.source.channel);
+
+    for (auto& c : song.channels) // Layer children (round 164)
+        for (auto& k : c.layer.children)
+            k = map (k);
 }
 
 bool moveChannels (Song& song, std::vector<int>& selection, int delta)

+ 80 - 3
src/core/RackRenderer.cpp

@@ -1,4 +1,5 @@
 #include "core/RackRenderer.h"
+#include "core/Layer.h"
 #include "core/FacetEq.h"
 #include "core/MidiControls.h"
 #include "core/Patcher.h"
@@ -408,6 +409,9 @@ std::unique_ptr<const RackState> RackState::build (Song song,
                     state->cutTargets[c].push_back ((int) d);
                     state->hasCutGroups = true;
                 }
+    state->hasLayers = std::any_of (channels.begin(), channels.end(), [] (const ChannelDef& c) {
+        return c.instrument == InstrumentKind::layer && ! c.layer.children.empty();
+    });
     const auto audible = state->song.soloAudible();
     state->mixerAudible.assign (audible.begin(), audible.end());
     loadtrace::add ("rack_schedule_graph", loadtrace::msSince (tailStarted));
@@ -1063,6 +1067,7 @@ void RackRenderer::prepare (double sr, int maxBlockSize)
     blockCapacity = std::max (64, maxBlockSize);
     mixBuffers.assign ((std::size_t) maxMixerTracks * 2 * (std::size_t) blockCapacity, 0.0f);
     hwScratch.assign (2 * (std::size_t) blockCapacity, 0.0f);
+    layerPick.assign ((std::size_t) maxChannels * 128, (std::int16_t) -1);
 
     if (lastState != nullptr)
     {
@@ -1422,7 +1427,9 @@ void RackRenderer::renderChannel (const RackState& state, int i, int n) noexcept
         {
             if (e.key >= 0 && e.key < 128)
                 held[(std::size_t) (e.key >> 6)] |= bit;
-            if (! c.muted)
+            // FL's key region (round 164): the channel plays only the notes inside it (audio clips: the key is the clip)
+            const auto inRegion = c.instrument == InstrumentKind::audioClip || c.inKeyRegion (list[index].key);
+            if (! c.muted && inRegion)
             {
                 // Max polyphony: the oldest note is released first
                 if (const auto limit = voiceLimitFor (c.maxPolyphony, c.synth.mono); limit > 0)
@@ -1444,8 +1451,9 @@ void RackRenderer::renderChannel (const RackState& state, int i, int n) noexcept
 
                 // an echo's volume: the instrument scales the voice, else (engines without it) the velocity
                 auto velocity = e.velocity;
-                if (gains != nullptr && gains[index] != 1.0f && ! instrument.setNextNoteGain (gains[index]))
-                    velocity *= gains[index];
+                const auto gain = e.gain * (gains != nullptr ? gains[index] : 1.0f);
+                if (gain != 1.0f && ! instrument.setNextNoteGain (gain))
+                    velocity *= gain;
                 instrument.noteOnAt (e.key, velocity, e.startSeconds);
             }
         }
@@ -1914,6 +1922,9 @@ void RackRenderer::process (const RackState* state,
                 continue;
             }
             auto& order = voiceOrders[(std::size_t) std::min (e.channel, maxChannels - 1)];
+            if (e.type == NoteEvent::Type::on && (std::size_t) e.channel < state->song.channels.size()
+                && ! state->song.channels[(std::size_t) e.channel].inKeyRegion (e.key))
+                continue; // outside the channel's key region (round 164)
             if (e.type == NoteEvent::Type::on)
             {
                 const auto& def = state->song.channels;
@@ -2071,11 +2082,73 @@ void RackRenderer::applyLiveControl (const RackState& state, const NoteEvent& e)
             }
 }
 
+void RackRenderer::expandLayers (const RackState& state) noexcept
+{
+    const auto& channels = state.song.channels;
+    const auto count = events.size();
+    auto added = false;
+    for (int i = 0; i < count; ++i)
+    {
+        const auto e = events[i];
+        if (e.channel < 0 || e.channel >= (int) channels.size() || e.channel >= maxChannels)
+            continue;
+        const auto& l = channels[(std::size_t) e.channel];
+        if (l.instrument != InstrumentKind::layer || l.layer.children.empty())
+            continue;
+        const auto key = std::clamp (e.key, 0, 127);
+        auto* picked = layerPick.empty() ? nullptr : &layerPick[(std::size_t) e.channel * 128 + (std::size_t) key];
+        auto child = e;
+        child.pan = std::clamp (e.pan + l.pan, -1.0f, 1.0f);
+        child.cents = e.cents + 100.0f * l.sampler.pitch;
+        const auto one = l.layer.random || l.layer.sequential;
+
+        if (e.type == NoteEvent::Type::on)
+        {
+            if (l.muted)
+                continue;
+            std::array<layer::Pick, 64> picks;
+            const auto n = layer::pick (l, channels, key, layerRandom, layerTurn[(std::size_t) e.channel], picks.data(), (int) picks.size());
+            if (one && picked != nullptr)
+                *picked = (std::int16_t) (n > 0 ? picks[0].child : -1);
+            const auto level = layer::levelGain (l);
+            for (int k = 0; k < n; ++k)
+            {
+                child.channel = picks[(std::size_t) k].child;
+                child.gain = e.gain * level * picks[(std::size_t) k].gain;
+                events.add (child);
+                added = true;
+            }
+        }
+        else if (e.type == NoteEvent::Type::off && one)
+        {
+            if (picked != nullptr && *picked >= 0)
+            {
+                child.channel = *picked;
+                *picked = -1;
+                events.add (child);
+                added = true;
+            }
+        }
+        else if (e.type == NoteEvent::Type::off || e.type == NoteEvent::Type::slide || e.type == NoteEvent::Type::choke)
+            for (const auto c : l.layer.children)
+                if (c >= 0 && c < (int) channels.size() && c != e.channel && channels[(std::size_t) c].instrument != InstrumentKind::layer)
+                {
+                    child.channel = c;
+                    events.add (child);
+                    added = true;
+                }
+    }
+    if (added)
+        events.sortByOffset();
+}
+
 bool RackRenderer::routesLiveNotes (const RackState& state, int channel) const noexcept
 {
     const auto c = (std::size_t) channel;
     if (channel < 0 || c >= state.song.channels.size())
         return false;
+    if (state.song.channels[c].instrument == InstrumentKind::layer) // (its children play the note: round 164)
+        return true;
     const auto& misc = state.song.channels[c].misc;
     return (c < state.arpeggiators.size() && state.arpeggiators[c] != nullptr) || (c < state.echoes.size() && state.echoes[c] != nullptr)
            || misc.key.pan != 0.0f || misc.velocity.pan != 0.0f
@@ -2166,6 +2239,10 @@ void RackRenderer::processChunk (const RackState& state, bool playing, double st
         events.sortByOffset();
     }
 
+    // Layer channels play their children (round 164)
+    if (state.hasLayers)
+        expandLayers (state);
+
     // cut groups: each note of a channel "cuts" the channels linked to it, at the same sample
     if (state.hasCutGroups)
     {

+ 8 - 0
src/core/RackRenderer.h

@@ -96,6 +96,8 @@ struct RackState
     // Cut groups: channels each channel cuts when it plays (cutBy == its cutGroup).
     std::vector<std::vector<int>> cutTargets;
     bool hasCutGroups = false;
+    // Layer channels (round 164): their notes play their children (RackRenderer::expandLayers)
+    bool hasLayers = false;
 
     // Mixer: insert processing order and which ones sound with the current solo.
     std::vector<int> mixerOrder;
@@ -347,6 +349,12 @@ private:
     int liveRoutedCount = 0;
     double liveTick = 0.0;
     bool routesLiveNotes (const RackState& state, int channel) const noexcept;
+    // Layer channels (round 164): each note event of a Layer is copied to the children it plays (core/Layer.h). The
+    // child a Random / Sequential note picked is kept per Layer and key so its "off" reaches the same child.
+    void expandLayers (const RackState& state) noexcept;
+    std::vector<std::int16_t> layerPick; // [channel * 128 + key]: the child, −1 none (maxChannels × 128)
+    std::array<int, maxChannels> layerTurn {};
+    std::uint32_t layerRandom = 0x2545F491u;
     void applyLiveControl (const RackState& state, const NoteEvent& e) noexcept;
     WorkerPool* workers = nullptr;
     LiveInput* liveInput = nullptr;

+ 3 - 0
src/core/Scheduler.h

@@ -37,6 +37,9 @@ struct NoteEvent
     float clipElapsed = 0.0f, clipRemaining = 0.0f, fadeIn = 0.0f, fadeOut = 0.0f;
     // the note's Mod X / Y (0..1, 0.5 = none) and, on its "off", its release velocity (0..1) — REA round 151
     float modX = 0.5f, modY = 0.5f, release = 0.5f;
+    // the note's level factor (a Layer's VOL and crossfade, round 164): the instrument scales the voice when it can,
+    // else the velocity is scaled
+    float gain = 1.0f;
 };
 
 // Fixed-capacity buffer. Events beyond capacity are dropped

+ 9 - 0
src/core/Song.cpp

@@ -242,6 +242,15 @@ void Song::removeChannel (int index)
         else if (automation.source.channel > index)
             --automation.source.channel;
 
+    for (auto& c : channels) // Layer children (round 164)
+    {
+        auto& kids = c.layer.children;
+        kids.erase (std::remove (kids.begin(), kids.end(), index), kids.end());
+        for (auto& k : kids)
+            if (k > index)
+                --k;
+    }
+
     removeDeadMidiLinks();
 }
 

+ 22 - 1
src/core/Song.h

@@ -79,7 +79,8 @@ enum class InstrumentKind : std::uint8_t
     midiOut,    // FL's MIDI Out (REA_rodada16 §1, REA_rodada133 §4): no sound; its notes and MIDI controls go to the plugins whose
                 // MIDI input port is its port (PluginRef::midiInPort). FL's state (channel @4, port @24) in pluginState
     patcher,    // FL's Patcher as a generator (REA_rodada141): a graph of instruments and effects in ChannelDef::patcher
-    soundfont   // LYNX Soundfont (REA_rodada158, core/SoundFont.h): the .sf2 / .sf3 in samplePath, settings in modelParams
+    soundfont,  // LYNX Soundfont (REA_rodada158, core/SoundFont.h): the .sf2 / .sf3 in samplePath, settings in modelParams
+    layer       // FL's Layer channel (REA_rodada164a, core/Layer.h): no sound; its notes play its children (ChannelDef::layer)
 };
 
 // External plugin: format identifier (the app knows how to find the file) + saved state.
@@ -495,6 +496,20 @@ struct ChannelMisc
     bool operator== (const ChannelMisc&) const = default;
 };
 
+// FL's Layer channel (REA_rodada164a §1, FL's manual "Layer channel settings"): it makes no sound; every note played on
+// it (Piano roll, steps, keyboard) plays its children channels. A child played from its own notes is not affected.
+struct LayerSettings
+{
+    std::vector<int> children; // channel indices ("Set children": the selected channels, in Channel Rack order)
+    bool random = false;     // one child at random per note (else every child)
+    bool crossfade = false;  // the Fade knob crossfades the children, top to bottom
+    bool sequential = false; // the children in turn (round robin), one per note
+    float fade = 0.0f;       // the Fade knob 0..1 (with crossfade)
+    // (the Layer's VOL / PAN are the channel's volume / pan, its PITCH the header's pitch knob: sampler.pitch)
+
+    bool operator== (const LayerSettings&) const = default;
+};
+
 struct ChannelDef
 {
     std::string name;
@@ -524,7 +539,13 @@ struct ChannelDef
     ChannelMisc misc;         // FL's Misc tab: time shift / gate, echo delay, velocity / key tracking (REA round 146b)
     // Piano Roll key labels (FL 2026's custom key labels, REA round 153): MIDI key -> the name shown on that key
     std::map<int, std::string> keyLabels;
+    // FL's key region (the Channel settings keyboard's ruler, REA_rodada164a §2): the channel plays only the notes
+    // from keyLow to keyHigh (MIDI keys); 0…127 = every note. Layer's "Split children" sets one key per child.
+    int keyLow = 0, keyHigh = 127;
+    LayerSettings layer; // instrument == layer: its children and options
 
+    bool hasKeyRegion() const noexcept { return keyLow > 0 || keyHigh < 127; }
+    bool inKeyRegion (int key) const noexcept { return key >= keyLow && key <= keyHigh; }
     bool operator== (const ChannelDef&) const = default;
 };
 

+ 34 - 1
src/engine/ProjectFile.cpp

@@ -115,6 +115,7 @@ const char* instrumentId (InstrumentKind k)
         case InstrumentKind::midiOut: return "midiOut";
         case InstrumentKind::patcher: return "patcher";
         case InstrumentKind::soundfont: return "soundfont";
+        case InstrumentKind::layer: return "layer";
     }
     return "synth";
 }
@@ -129,7 +130,7 @@ InstrumentKind instrumentFromId (const juce::String& id)
                     InstrumentKind::fruitkick, InstrumentKind::bassdrum, InstrumentKind::toxic,
                     InstrumentKind::threeosc, InstrumentKind::autogun, InstrumentKind::transistorbass,
                     InstrumentKind::simsynth, InstrumentKind::wasp, InstrumentKind::plucked, InstrumentKind::beepmap, InstrumentKind::sawer, InstrumentKind::flkeys,
-                    InstrumentKind::granulizer, InstrumentKind::drumaxx, InstrumentKind::slayer, InstrumentKind::fruitydance, InstrumentKind::directwave, InstrumentKind::midiOut, InstrumentKind::patcher, InstrumentKind::soundfont })
+                    InstrumentKind::granulizer, InstrumentKind::drumaxx, InstrumentKind::slayer, InstrumentKind::fruitydance, InstrumentKind::directwave, InstrumentKind::midiOut, InstrumentKind::patcher, InstrumentKind::soundfont, InstrumentKind::layer })
         if (id == instrumentId (k))
             return k;
 
@@ -889,6 +890,22 @@ juce::var channelToVar (const ChannelDef& c)
     }
     if (c.cutGroup != 0 || c.cutBy != 0)
         o->setProperty ("cut", juce::Array<juce::var> { c.cutGroup, c.cutBy });
+    // FL's key region and Layer channels (round 164)
+    if (c.hasKeyRegion())
+        o->setProperty ("keyRegion", juce::Array<juce::var> { c.keyLow, c.keyHigh });
+    if (c.instrument == InstrumentKind::layer)
+    {
+        auto l = std::make_unique<juce::DynamicObject>();
+        juce::Array<juce::var> kids;
+        for (const auto k : c.layer.children)
+            kids.add (k);
+        l->setProperty ("children", kids);
+        l->setProperty ("random", c.layer.random);
+        l->setProperty ("crossfade", c.layer.crossfade);
+        l->setProperty ("sequential", c.layer.sequential);
+        l->setProperty ("fade", c.layer.fade);
+        o->setProperty ("layer", juce::var (l.release()));
+    }
 
     if (! (c.synth == SynthSettings {}))
     {
@@ -1103,6 +1120,22 @@ ChannelDef channelFromVar (const juce::var& c, const Song& song)
             def.arp.octaveRepeat = juce::jlimit (0, 16, (int) fl.getProperty ("octaveRepeat", 1));
         }
     }
+    if (const auto& region = c["keyRegion"]; region.isArray() && region.size() >= 2)
+    {
+        def.keyLow = juce::jlimit (0, 127, (int) region[0]);
+        def.keyHigh = juce::jlimit (def.keyLow, 127, (int) region[1]);
+    }
+    if (const auto& l = c["layer"]; l.isObject())
+    {
+        if (const auto* kids = l["children"].getArray())
+            for (const auto& k : *kids)
+                if ((int) k >= 0)
+                    def.layer.children.push_back ((int) k);
+        def.layer.random = (bool) l.getProperty ("random", false);
+        def.layer.crossfade = (bool) l.getProperty ("crossfade", false);
+        def.layer.sequential = (bool) l.getProperty ("sequential", false);
+        def.layer.fade = juce::jlimit (0.0f, 1.0f, (float) (double) l.getProperty ("fade", 0.0));
+    }
     if (const auto& misc = c["misc"]; misc.isObject())
     {
         auto& m = def.misc;

+ 12 - 0
src/flp/Flp.cpp

@@ -15,6 +15,8 @@ enum : std::uint32_t
     evPanLaw = 0x17,
     evTimeSignatureNumerator = 0x11,
     evChannelSwingMix = 0x61,
+    evLayerChild = 0x5E,  // u16: a Layer channel's child (one event per child; REA_rodada164a §1)
+    evLayerFlags = 0x90,  // u32: a Layer channel's options (REA_rodada164a §1)
     evChannelTimeShift = 0x59,  // u16: Misc › Time › Shift, FL's time-knob value (REA round 146b)
     evChannelEcho = 0xD1,       // i32 feedback, pan, pitch, echoes, time (REA round 146b)
     evChannelEchoModXY = 0x8A,  // u16 mod X, u16 mod Y of the echoes (128 = none)
@@ -478,6 +480,16 @@ Project parseProject (std::span<const std::uint8_t> file, bool channelPreset)
                     channel().swingMix = (int) e.value;
                 break;
 
+            case evLayerChild:
+                if (section == Section::channel)
+                    channel().layerChildren.push_back ((int) e.value);
+                break;
+
+            case evLayerFlags:
+                if (section == Section::channel)
+                    channel().layerFlags = (int) e.value;
+                break;
+
             case evChannelTimeShift:
                 if (section == Section::channel)
                     channel().timeShift = (int) e.value;

+ 4 - 0
src/flp/Flp.h

@@ -107,6 +107,10 @@ struct Channel
     std::vector<std::uint8_t> pluginState; // the generator's 0xD5 (e.g. 3x Osc state)
     int wrapperFlags = -1;                 // the generator's 0xD4 u16 at +16 (0x10 generator, 0x20 smart disable; −1 = none)
 
+    // Layer channels (type layer, REA_rodada164a §1): 0x5E = a child channel's index (one per child), 0x90 = options
+    std::vector<int> layerChildren;
+    int layerFlags = 0;
+
     int swingMix = 128;          // 0x61: 0..128
     int cutGroup = 0, cutBy = 0; // 0x84
     int rootNote = -1;           // 0x87 (MIDI), -1 = default (C5 = 60)

+ 10 - 0
src/ui/ChannelRackComponent.cpp

@@ -79,6 +79,7 @@ juce::String instrumentName (InstrumentKind k)
         case InstrumentKind::midiOut: return "MIDI Out";
         case InstrumentKind::patcher: return "Patcher";
         case InstrumentKind::soundfont: return "LYNX Soundfont";
+        case InstrumentKind::layer: return "Layer";
     }
     return "?";
 }
@@ -97,6 +98,7 @@ juce::String instrumentLabel (InstrumentKind k)
         case InstrumentKind::audioClip: return tr ("Audio clip");
         case InstrumentKind::controller: return tr ("Envelope Controller");
         case InstrumentKind::midiOut: return tr ("MIDI Out");
+        case InstrumentKind::layer: return tr ("Layer");
         default: return instrumentName (k);
     }
 }
@@ -2101,6 +2103,14 @@ void ChannelRackComponent::addInstrumentItems (juce::PopupMenu& menu, int insert
         const auto added = add (c);
         openChannelSettings (engine, added);
     });
+    // FL's Layer (round 164): plays its children (its settings open: select channels, then Set children)
+    menu.addItem (tr ("Layer"), [this, add] {
+        ChannelDef c;
+        c.name = tr ("Layer").toStdString();
+        c.instrument = InstrumentKind::layer;
+        const auto added = add (c);
+        openChannelSettings (engine, added);
+    });
     // FL's own instrument engines (round 142, issue #5): their editor opens
     {
         juce::PopupMenu engines;

+ 98 - 7
src/ui/ChannelSettings.cpp

@@ -1,5 +1,6 @@
 #include "ui/WindowOwner.h"
 #include "ui/ChannelSettings.h"
+#include "ui/LayerEditor.h"
 
 #include "core/MixerOps.h"
 
@@ -2298,21 +2299,46 @@ class RootKeyboard final : public juce::Component, public juce::SettableTooltipC
 {
 public:
     std::function<void (int)> onPick;
+    // FL's key region ruler (round 164): a drag on the strip above the keys sets the notes the channel plays,
+    // a double-click there gives it the whole keyboard back
+    std::function<void (int, int)> onRegion;
     void setRoot (int key)
     {
         root = key;
         repaint();
     }
+    void setRegion (int low, int high)
+    {
+        if (low != regionLow || high != regionHigh)
+        {
+            regionLow = low;
+            regionHigh = high;
+            repaint();
+        }
+    }
 
     void paint (juce::Graphics& g) override
     {
         using namespace theme;
         const auto w = whiteWidth();
+        const auto top = (float) rulerHeight();
+        const auto keysH = (float) getHeight() - top;
+        if (onRegion)
+        {
+            const auto ruler = juce::Rectangle<float> (0.0f, 0.0f, (float) getWidth(), top - 2.0f);
+            g.setColour (colour::bg0);
+            g.fillRect (ruler);
+            const auto full = regionLow <= 0 && regionHigh >= 127;
+            const auto x0 = keyLeft (regionLow), x1 = keyRight (regionHigh);
+            g.setColour (full ? colour::bg5 : colour::accent);
+            g.fillRect (juce::Rectangle<float> (x0, 1.0f, juce::jmax (2.0f, x1 - x0), ruler.getHeight() - 2.0f));
+        }
         for (int k = 0, white = 0; k < 128; ++k)
             if (! isBlack (k))
             {
-                const auto r = juce::Rectangle<float> ((float) (white++) * w, 0.0f, w - 1.0f, (float) getHeight());
-                g.setColour (k == root ? colour::accent : k == hover ? juce::Colour (0xffc8ccd4) : juce::Colour (0xffe6e8ec));
+                const auto r = juce::Rectangle<float> ((float) (white++) * w, top, w - 1.0f, keysH);
+                const auto outside = onRegion && (k < regionLow || k > regionHigh);
+                g.setColour (k == root ? colour::accent : k == hover ? juce::Colour (0xffc8ccd4) : outside ? juce::Colour (0xff9a9ea8) : juce::Colour (0xffe6e8ec));
                 g.fillRect (r);
                 if (k % 12 == 0 && w * 7.0f >= 14.0f) // the octave's C named (FL's C5 = 60)
                 {
@@ -2327,16 +2353,22 @@ public:
             {
                 const auto x = (float) whitesBefore (k) * w - w * 0.32f;
                 g.setColour (k == root ? colour::accent : k == hover ? colour::bg5 : colour::bg0);
-                g.fillRect (juce::Rectangle<float> (x, 0.0f, w * 0.64f, (float) getHeight() * 0.6f));
+                g.fillRect (juce::Rectangle<float> (x, top, w * 0.64f, keysH * 0.6f));
             }
     }
 
     void mouseMove (const juce::MouseEvent& e) override
     {
-        if (const auto k = keyAt (e.position); k != hover)
+        const auto onRuler = onRegion && e.position.y < (float) rulerHeight();
+        if (const auto k = keyAt (e.position); k != hover || onRuler != hoverRuler)
         {
             hover = k;
-            setTooltip (k >= 0 ? tr ("Root note: {0}", { keyName (k) }) : juce::String());
+            hoverRuler = onRuler;
+            if (onRuler)
+                setTooltip (tr ("Key region: {0} to {1} (drag to set, double-click for the whole keyboard)",
+                                { keyName (regionLow), keyName (regionHigh) }));
+            else
+                setTooltip (k >= 0 ? tr ("Root note: {0}", { keyName (k) }) : juce::String());
             repaint();
         }
     }
@@ -2347,9 +2379,30 @@ public:
     }
     void mouseDown (const juce::MouseEvent& e) override
     {
+        dragFrom = -1;
+        if (onRegion && e.position.y < (float) rulerHeight())
+        {
+            dragFrom = keyAtX (e.position.x);
+            if (dragFrom >= 0)
+                onRegion (dragFrom, dragFrom);
+            return;
+        }
         if (const auto k = keyAt (e.position); k >= 0 && onPick)
             onPick (k);
     }
+    void mouseDrag (const juce::MouseEvent& e) override
+    {
+        if (dragFrom < 0 || ! onRegion)
+            return;
+        const auto k = keyAtX (e.position.x);
+        if (k >= 0)
+            onRegion (juce::jmin (dragFrom, k), juce::jmax (dragFrom, k));
+    }
+    void mouseDoubleClick (const juce::MouseEvent& e) override
+    {
+        if (onRegion && e.position.y < (float) rulerHeight())
+            onRegion (0, 127);
+    }
 
     static juce::String keyName (int key)
     {
@@ -2370,11 +2423,37 @@ private:
             count += isBlack (i) ? 0 : 1;
         return count;
     }
+    int rulerHeight() const noexcept { return onRegion ? 9 : 0; }
     float whiteWidth() const noexcept { return (float) getWidth() / 75.0f; } // 75 white keys in 0…127
+    float keyLeft (int k) const noexcept
+    {
+        const auto w = whiteWidth();
+        return isBlack (k) ? (float) whitesBefore (k) * w - w * 0.32f : (float) whitesBefore (k) * w;
+    }
+    float keyRight (int k) const noexcept
+    {
+        const auto w = whiteWidth();
+        return isBlack (k) ? keyLeft (k) + w * 0.64f : keyLeft (k) + w;
+    }
+    // the key under x on the ruler (each key owns its own horizontal span; black keys win where they overlap)
+    int keyAtX (float x) const noexcept
+    {
+        for (int k = 0; k < 128; ++k)
+            if (isBlack (k) && x >= keyLeft (k) && x < keyRight (k))
+                return k;
+        const auto white = (int) std::floor (x / whiteWidth());
+        for (int k = 0, n = 0; k < 128; ++k)
+            if (! isBlack (k) && n++ == white)
+                return k;
+        return x < 0.0f ? 0 : 127;
+    }
     int keyAt (juce::Point<float> p) const noexcept
     {
         const auto w = whiteWidth();
-        if (p.y < (float) getHeight() * 0.6f)
+        const auto top = (float) rulerHeight();
+        if (p.y < top)
+            return keyAtX (p.x);
+        if (p.y < top + ((float) getHeight() - top) * 0.6f)
             for (int k = 0; k < 128; ++k)
                 if (isBlack (k))
                 {
@@ -2389,7 +2468,9 @@ private:
         return -1;
     }
 
-    int root = 60, hover = -1;
+    int root = 60, hover = -1, dragFrom = -1;
+    int regionLow = 0, regionHigh = 127;
+    bool hoverRuler = false;
 };
 
 class MiscPanel final : public juce::Component,
@@ -2645,6 +2726,12 @@ public:
                     d.misc.rootNote = key;
             });
         };
+        rootKeys.onRegion = [this] (int low, int high) {
+            edit ([low, high] (ChannelDef& d) {
+                d.keyLow = juce::jlimit (0, 127, low);
+                d.keyHigh = juce::jlimit (d.keyLow, 127, high);
+            });
+        };
         addAndMakeVisible (addToKey);
         addAndMakeVisible (rootKeys);
         // Arpeggiator: FL's Slide and Chord
@@ -2893,6 +2980,7 @@ private:
         addToKey.setToggleState (c->misc.addToKey, juce::dontSendNotification);
         addToKey.setEnabled (c->instrument != InstrumentKind::sampler);
         rootKeys.setRoot (c->misc.rootNote);
+        rootKeys.setRegion (c->keyLow, c->keyHigh);
         arpSlide.setToggleState (c->arp.slide, juce::dontSendNotification);
         const auto filter = c->instrument == InstrumentKind::synth || c->instrument == InstrumentKind::sampler;
         modX->setEnabled (filter);
@@ -3265,6 +3353,7 @@ bool hasChannelSettings (InstrumentKind kind) noexcept
         case InstrumentKind::fruitydance:
         case InstrumentKind::sytrus:
         case InstrumentKind::soundfont:
+        case InstrumentKind::layer:
             return true;
         default:
             return false;
@@ -3311,6 +3400,8 @@ std::unique_ptr<juce::Component> makeChannelSettingsPanel (AudioEngine& engine,
         return makeMidiOutEditor (engine, channel);
     if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::soundfont)
         return makeSoundFontEditor (engine, channel);
+    if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::layer)
+        return makeLayerEditor (engine, channel);
     if (const auto kind = engine.getSong().channels[(std::size_t) channel].instrument;
         kind == InstrumentKind::sakura || kind == InstrumentKind::drumpad || kind == InstrumentKind::boobass
                  || kind == InstrumentKind::drumsynth || kind == InstrumentKind::harmless || kind == InstrumentKind::harmor

+ 3 - 108
src/ui/ControllerEditors.cpp

@@ -14,124 +14,19 @@
 #include "ui/I18n.h"
 #include "ui/Theme.h"
 #include "ui/ValueControl.h"
+#include "ui/ControllerKnob.h"
 
 namespace lynx
 {
 namespace
 {
+using ctlui::Knob;
+using ctlui::unitSpec;
 juce::String nameOf (const std::string& s)
 {
     return juce::String::fromUTF8 (s.c_str());
 }
 
-// A small rotary control with LYNX's control contract (drag, Ctrl = fine, wheel, Alt / middle-click reset, right-click
-// menu with automation and controller links when `spec.target` is set).
-class Knob final : public juce::Component
-{
-public:
-    Knob (AudioEngine* e, ui::ValueSpec s, std::function<double()> get, std::function<void (double)> set)
-        : engine (e), spec (std::move (s)), getter (std::move (get)), setter (std::move (set))
-    {
-        setRepaintsOnMouseActivity (true);
-        ui::setHint (*this, spec.name, true, spec.target.has_value());
-    }
-
-    void paint (juce::Graphics& g) override
-    {
-        const auto v = juce::jlimit (0.0, 1.0, (getter() - spec.minimum) / juce::jmax (1e-9, spec.maximum - spec.minimum));
-        auto area = getLocalBounds().toFloat();
-        const auto label = area.removeFromBottom (14.0f);
-        const auto valueArea = area.removeFromBottom (13.0f);
-        const auto size = juce::jmin (area.getWidth(), area.getHeight()) - 4.0f;
-        const auto box = juce::Rectangle<float> (size, size).withCentre (area.getCentre());
-        constexpr float sweep = juce::MathConstants<float>::pi * 1.5f;
-
-        g.setColour (theme::colour::bg4);
-        g.fillEllipse (box.reduced (4.0f));
-        juce::Path track, arc;
-        const auto radius = size * 0.5f - 1.5f;
-        track.addCentredArc (box.getCentreX(), box.getCentreY(), radius, radius, 0.0f, -sweep * 0.5f, sweep * 0.5f, true);
-        g.setColour (theme::colour::bg6);
-        g.strokePath (track, juce::PathStrokeType (3.0f));
-        arc.addCentredArc (box.getCentreX(), box.getCentreY(), radius, radius, 0.0f, -sweep * 0.5f, -sweep * 0.5f + sweep * (float) v, true);
-        g.setColour (isMouseOverOrDragging() ? theme::colour::accent : theme::colour::knobArc);
-        g.strokePath (arc, juce::PathStrokeType (3.0f));
-
-        g.setColour (theme::colour::textPrimary);
-        g.setFont (theme::font (theme::type::caption));
-        g.drawText (spec.text (getter()), valueArea, juce::Justification::centred);
-        g.setColour (theme::colour::textSecondary);
-        g.drawText (shortName.isNotEmpty() ? shortName : spec.name, label, juce::Justification::centred);
-    }
-
-    void mouseDown (const juce::MouseEvent& e) override
-    {
-        if (e.mods.isPopupMenu())
-        {
-            ui::showValueMenu (*this, engine, spec, getter(), setter);
-            return;
-        }
-        if (ui::isResetClick (e))
-        {
-            setter (spec.defaultValue);
-            repaint();
-            return;
-        }
-        drag.begin (e, getter());
-    }
-
-    void mouseDrag (const juce::MouseEvent& e) override
-    {
-        if (! drag.isActive())
-            return;
-        setter (drag.update (e, spec));
-        ui::showValueTip (*this, getLocalBounds(), spec.text (getter()));
-        repaint();
-    }
-
-    void mouseUp (const juce::MouseEvent&) override
-    {
-        drag.end();
-        ui::hideValueTip();
-    }
-
-    void mouseDoubleClick (const juce::MouseEvent&) override
-    {
-        setter (spec.defaultValue);
-        repaint();
-    }
-
-    void mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel) override
-    {
-        if (const auto v = ui::wheelValue (getter(), e, wheel, spec))
-        {
-            setter (*v);
-            ui::flashValueTip (*this, getLocalBounds(), spec.text (getter()));
-            repaint();
-        }
-    }
-
-    juce::String shortName;
-
-private:
-    AudioEngine* engine;
-    ui::ValueSpec spec;
-    std::function<double()> getter;
-    std::function<void (double)> setter;
-    ui::ValueDrag drag;
-};
-
-ui::ValueSpec unitSpec (const juce::String& name, double def, std::optional<AutomationTarget> target)
-{
-    ui::ValueSpec s;
-    s.name = name;
-    s.defaultValue = def;
-    s.toText = [] (double v) { return juce::String (v, 3); };
-    s.fromText = [] (const juce::String& t) -> std::optional<double> { return juce::jlimit (0.0, 1.0, t.getDoubleValue()); };
-    s.target = target;
-    return s;
-}
-
 // The history of a control output, drawn as FL's controller monitors do.
 class Monitor final : public juce::Component
 {

+ 122 - 0
src/ui/ControllerKnob.h

@@ -0,0 +1,122 @@
+#pragma once
+
+// The small rotary control of the controller editors (round 133; shared with the round 164 editors: Layer, X-Y / X-Y-Z
+// Controller, Control Surface, Voltage Controller).
+
+#include "engine/AudioEngine.h"
+#include "ui/AutomationUi.h"
+#include "ui/I18n.h"
+#include "ui/Theme.h"
+#include "ui/ValueControl.h"
+
+namespace lynx::ctlui
+{
+// A small rotary control with LYNX's control contract (drag, Ctrl = fine, wheel, Alt / middle-click reset, right-click
+// menu with automation and controller links when `spec.target` is set).
+class Knob final : public juce::Component
+{
+public:
+    Knob (AudioEngine* e, ui::ValueSpec s, std::function<double()> get, std::function<void (double)> set)
+        : engine (e), spec (std::move (s)), getter (std::move (get)), setter (std::move (set))
+    {
+        setRepaintsOnMouseActivity (true);
+        ui::setHint (*this, spec.name, true, spec.target.has_value());
+    }
+
+    void paint (juce::Graphics& g) override
+    {
+        const auto v = juce::jlimit (0.0, 1.0, (getter() - spec.minimum) / juce::jmax (1e-9, spec.maximum - spec.minimum));
+        auto area = getLocalBounds().toFloat();
+        const auto label = area.removeFromBottom (14.0f);
+        const auto valueArea = area.removeFromBottom (13.0f);
+        const auto size = juce::jmin (area.getWidth(), area.getHeight()) - 4.0f;
+        const auto box = juce::Rectangle<float> (size, size).withCentre (area.getCentre());
+        constexpr float sweep = juce::MathConstants<float>::pi * 1.5f;
+
+        g.setColour (theme::colour::bg4);
+        g.fillEllipse (box.reduced (4.0f));
+        juce::Path track, arc;
+        const auto radius = size * 0.5f - 1.5f;
+        track.addCentredArc (box.getCentreX(), box.getCentreY(), radius, radius, 0.0f, -sweep * 0.5f, sweep * 0.5f, true);
+        g.setColour (theme::colour::bg6);
+        g.strokePath (track, juce::PathStrokeType (3.0f));
+        arc.addCentredArc (box.getCentreX(), box.getCentreY(), radius, radius, 0.0f, -sweep * 0.5f, -sweep * 0.5f + sweep * (float) v, true);
+        g.setColour (isMouseOverOrDragging() ? theme::colour::accent : theme::colour::knobArc);
+        g.strokePath (arc, juce::PathStrokeType (3.0f));
+
+        g.setColour (theme::colour::textPrimary);
+        g.setFont (theme::font (theme::type::caption));
+        g.drawText (spec.text (getter()), valueArea, juce::Justification::centred);
+        g.setColour (theme::colour::textSecondary);
+        g.drawText (shortName.isNotEmpty() ? shortName : spec.name, label, juce::Justification::centred);
+    }
+
+    void mouseDown (const juce::MouseEvent& e) override
+    {
+        if (e.mods.isPopupMenu())
+        {
+            ui::showValueMenu (*this, engine, spec, getter(), setter);
+            return;
+        }
+        if (ui::isResetClick (e))
+        {
+            setter (spec.defaultValue);
+            repaint();
+            return;
+        }
+        drag.begin (e, getter());
+    }
+
+    void mouseDrag (const juce::MouseEvent& e) override
+    {
+        if (! drag.isActive())
+            return;
+        setter (drag.update (e, spec));
+        ui::showValueTip (*this, getLocalBounds(), spec.text (getter()));
+        repaint();
+    }
+
+    void mouseUp (const juce::MouseEvent&) override
+    {
+        drag.end();
+        ui::hideValueTip();
+    }
+
+    void mouseDoubleClick (const juce::MouseEvent&) override
+    {
+        setter (spec.defaultValue);
+        repaint();
+    }
+
+    void mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel) override
+    {
+        if (const auto v = ui::wheelValue (getter(), e, wheel, spec))
+        {
+            setter (*v);
+            ui::flashValueTip (*this, getLocalBounds(), spec.text (getter()));
+            repaint();
+        }
+    }
+
+    juce::String shortName;
+
+private:
+    AudioEngine* engine;
+    ui::ValueSpec spec;
+    std::function<double()> getter;
+    std::function<void (double)> setter;
+    ui::ValueDrag drag;
+};
+
+inline ui::ValueSpec unitSpec (const juce::String& name, double def, std::optional<AutomationTarget> target)
+{
+    ui::ValueSpec s;
+    s.name = name;
+    s.defaultValue = def;
+    s.toText = [] (double v) { return juce::String (v, 3); };
+    s.fromText = [] (const juce::String& t) -> std::optional<double> { return juce::jlimit (0.0, 1.0, t.getDoubleValue()); };
+    s.target = target;
+    return s;
+}
+
+} // namespace lynx::ctlui

+ 100 - 1
src/ui/I18nData.h

@@ -14304,6 +14304,105 @@ inline constexpr unsigned char ptBR[] = {
 34, 32, 61, 32, 34, 66, 114, 111, 119, 115, 101, 114, 32, 100, 101, 32, 115, 97, 109, 112, 108, 101, 115, 34,
 10, 34, 79, 112, 101, 110, 32, 105, 110, 32, 116, 104, 101, 32, 102, 105, 108, 101, 32, 109, 97, 110, 97, 103,
 101, 114, 34, 32, 61, 32, 34, 65, 98, 114, 105, 114, 32, 110, 111, 32, 103, 101, 114, 101, 110, 99, 105, 97,
-100, 111, 114, 32, 100, 101, 32, 97, 114, 113, 117, 105, 118, 111, 115, 34, 10,
+100, 111, 114, 32, 100, 101, 32, 97, 114, 113, 117, 105, 118, 111, 115, 34, 10, 10, 35, 32, 114, 111, 117, 110,
+100, 32, 49, 54, 52, 97, 58, 32, 76, 97, 121, 101, 114, 32, 99, 104, 97, 110, 110, 101, 108, 10, 34, 76,
+97, 121, 101, 114, 34, 32, 61, 32, 34, 76, 97, 121, 101, 114, 34, 10, 34, 75, 101, 121, 32, 114, 101, 103,
+105, 111, 110, 58, 32, 123, 48, 125, 32, 116, 111, 32, 123, 49, 125, 32, 40, 100, 114, 97, 103, 32, 116, 111,
+32, 115, 101, 116, 44, 32, 100, 111, 117, 98, 108, 101, 45, 99, 108, 105, 99, 107, 32, 102, 111, 114, 32, 116,
+104, 101, 32, 119, 104, 111, 108, 101, 32, 107, 101, 121, 98, 111, 97, 114, 100, 41, 34, 32, 61, 32, 34, 82,
+101, 103, 105, 195, 163, 111, 32, 100, 101, 32, 116, 101, 99, 108, 97, 115, 58, 32, 123, 48, 125, 32, 97, 32,
+123, 49, 125, 32, 40, 97, 114, 114, 97, 115, 116, 101, 32, 112, 97, 114, 97, 32, 100, 101, 102, 105, 110, 105,
+114, 44, 32, 99, 108, 105, 113, 117, 101, 32, 100, 117, 112, 108, 111, 32, 112, 97, 114, 97, 32, 111, 32, 116,
+101, 99, 108, 97, 100, 111, 32, 105, 110, 116, 101, 105, 114, 111, 41, 34, 10, 34, 83, 101, 116, 32, 99, 104,
+105, 108, 100, 114, 101, 110, 34, 32, 61, 32, 34, 68, 101, 102, 105, 110, 105, 114, 32, 102, 105, 108, 104, 111,
+115, 34, 10, 34, 84, 104, 101, 32, 99, 104, 97, 110, 110, 101, 108, 115, 32, 115, 101, 108, 101, 99, 116, 101,
+100, 32, 105, 110, 32, 116, 104, 101, 32, 67, 104, 97, 110, 110, 101, 108, 32, 82, 97, 99, 107, 32, 98, 101,
+99, 111, 109, 101, 32, 116, 104, 105, 115, 32, 76, 97, 121, 101, 114, 39, 115, 32, 99, 104, 105, 108, 100, 114,
+101, 110, 32, 40, 115, 101, 108, 101, 99, 116, 32, 116, 104, 101, 32, 111, 110, 101, 115, 32, 116, 111, 32, 107,
+101, 101, 112, 32, 97, 110, 100, 32, 112, 114, 101, 115, 115, 32, 97, 103, 97, 105, 110, 32, 116, 111, 32, 114,
+101, 109, 111, 118, 101, 32, 111, 110, 101, 41, 34, 32, 61, 32, 34, 79, 115, 32, 99, 97, 110, 97, 105, 115,
+32, 115, 101, 108, 101, 99, 105, 111, 110, 97, 100, 111, 115, 32, 110, 111, 32, 67, 104, 97, 110, 110, 101, 108,
+32, 82, 97, 99, 107, 32, 118, 105, 114, 97, 109, 32, 102, 105, 108, 104, 111, 115, 32, 100, 101, 115, 116, 101,
+32, 76, 97, 121, 101, 114, 32, 40, 115, 101, 108, 101, 99, 105, 111, 110, 101, 32, 111, 115, 32, 113, 117, 101,
+32, 102, 105, 99, 97, 109, 32, 101, 32, 99, 108, 105, 113, 117, 101, 32, 100, 101, 32, 110, 111, 118, 111, 32,
+112, 97, 114, 97, 32, 114, 101, 109, 111, 118, 101, 114, 32, 117, 109, 41, 34, 10, 34, 83, 104, 111, 119, 32,
+99, 104, 105, 108, 100, 114, 101, 110, 34, 32, 61, 32, 34, 77, 111, 115, 116, 114, 97, 114, 32, 102, 105, 108,
+104, 111, 115, 34, 10, 34, 83, 101, 108, 101, 99, 116, 115, 32, 116, 104, 105, 115, 32, 76, 97, 121, 101, 114,
+39, 115, 32, 99, 104, 105, 108, 100, 114, 101, 110, 32, 105, 110, 32, 116, 104, 101, 32, 67, 104, 97, 110, 110,
+101, 108, 32, 82, 97, 99, 107, 34, 32, 61, 32, 34, 83, 101, 108, 101, 99, 105, 111, 110, 97, 32, 111, 115,
+32, 102, 105, 108, 104, 111, 115, 32, 100, 101, 115, 116, 101, 32, 76, 97, 121, 101, 114, 32, 110, 111, 32, 67,
+104, 97, 110, 110, 101, 108, 32, 82, 97, 99, 107, 34, 10, 34, 76, 97, 121, 101, 114, 105, 110, 103, 34, 32,
+61, 32, 34, 67, 97, 109, 97, 100, 97, 115, 34, 10, 34, 83, 112, 108, 105, 116, 44, 32, 114, 101, 115, 101,
+116, 44, 32, 103, 114, 111, 117, 112, 32, 111, 114, 32, 100, 101, 108, 101, 116, 101, 32, 116, 104, 101, 32, 99,
+104, 105, 108, 100, 114, 101, 110, 34, 32, 61, 32, 34, 68, 105, 118, 105, 100, 105, 114, 44, 32, 114, 101, 100,
+101, 102, 105, 110, 105, 114, 44, 32, 97, 103, 114, 117, 112, 97, 114, 32, 111, 117, 32, 101, 120, 99, 108, 117,
+105, 114, 32, 111, 115, 32, 102, 105, 108, 104, 111, 115, 34, 10, 34, 82, 97, 110, 100, 111, 109, 58, 32, 101,
+97, 99, 104, 32, 110, 111, 116, 101, 32, 112, 108, 97, 121, 115, 32, 111, 110, 101, 32, 99, 104, 105, 108, 100,
+32, 112, 105, 99, 107, 101, 100, 32, 97, 116, 32, 114, 97, 110, 100, 111, 109, 32, 40, 118, 97, 114, 105, 101,
+100, 32, 104, 105, 116, 115, 41, 59, 32, 111, 102, 102, 32, 61, 32, 101, 118, 101, 114, 121, 32, 99, 104, 105,
+108, 100, 32, 112, 108, 97, 121, 115, 34, 32, 61, 32, 34, 65, 108, 101, 97, 116, 195, 179, 114, 105, 111, 58,
+32, 99, 97, 100, 97, 32, 110, 111, 116, 97, 32, 116, 111, 99, 97, 32, 117, 109, 32, 102, 105, 108, 104, 111,
+32, 115, 111, 114, 116, 101, 97, 100, 111, 32, 40, 98, 97, 116, 105, 100, 97, 115, 32, 118, 97, 114, 105, 97,
+100, 97, 115, 41, 59, 32, 100, 101, 115, 108, 105, 103, 97, 100, 111, 32, 61, 32, 116, 111, 100, 111, 115, 32,
+111, 115, 32, 102, 105, 108, 104, 111, 115, 32, 116, 111, 99, 97, 109, 34, 10, 34, 83, 101, 113, 117, 101, 110,
+116, 105, 97, 108, 34, 32, 61, 32, 34, 83, 101, 113, 117, 101, 110, 99, 105, 97, 108, 34, 10, 34, 83, 101,
+113, 117, 101, 110, 116, 105, 97, 108, 58, 32, 116, 104, 101, 32, 99, 104, 105, 108, 100, 114, 101, 110, 32, 112,
+108, 97, 121, 32, 105, 110, 32, 116, 117, 114, 110, 44, 32, 111, 110, 101, 32, 112, 101, 114, 32, 110, 111, 116,
+101, 32, 40, 114, 111, 117, 110, 100, 32, 114, 111, 98, 105, 110, 41, 34, 32, 61, 32, 34, 83, 101, 113, 117,
+101, 110, 99, 105, 97, 108, 58, 32, 111, 115, 32, 102, 105, 108, 104, 111, 115, 32, 116, 111, 99, 97, 109, 32,
+101, 109, 32, 114, 101, 118, 101, 122, 97, 109, 101, 110, 116, 111, 44, 32, 117, 109, 32, 112, 111, 114, 32, 110,
+111, 116, 97, 32, 40, 114, 111, 117, 110, 100, 32, 114, 111, 98, 105, 110, 41, 34, 10, 34, 67, 114, 111, 115,
+115, 102, 97, 100, 101, 34, 32, 61, 32, 34, 67, 114, 111, 115, 115, 102, 97, 100, 101, 34, 10, 34, 67, 114,
+111, 115, 115, 102, 97, 100, 101, 58, 32, 116, 104, 101, 32, 70, 97, 100, 101, 32, 107, 110, 111, 98, 32, 109,
+111, 118, 101, 115, 32, 102, 114, 111, 109, 32, 116, 104, 101, 32, 102, 105, 114, 115, 116, 32, 99, 104, 105, 108,
+100, 32, 116, 111, 32, 116, 104, 101, 32, 108, 97, 115, 116, 44, 32, 98, 108, 101, 110, 100, 105, 110, 103, 32,
+110, 101, 105, 103, 104, 98, 111, 117, 114, 115, 34, 32, 61, 32, 34, 67, 114, 111, 115, 115, 102, 97, 100, 101,
+58, 32, 111, 32, 107, 110, 111, 98, 32, 70, 97, 100, 101, 32, 118, 97, 105, 32, 100, 111, 32, 112, 114, 105,
+109, 101, 105, 114, 111, 32, 102, 105, 108, 104, 111, 32, 97, 111, 32, 195, 186, 108, 116, 105, 109, 111, 44, 32,
+109, 105, 115, 116, 117, 114, 97, 110, 100, 111, 32, 111, 115, 32, 118, 105, 122, 105, 110, 104, 111, 115, 34, 10,
+34, 76, 97, 121, 101, 114, 32, 45, 32, 70, 97, 100, 101, 32, 40, 99, 114, 111, 115, 115, 102, 97, 100, 101,
+32, 112, 111, 115, 105, 116, 105, 111, 110, 41, 34, 32, 61, 32, 34, 76, 97, 121, 101, 114, 32, 45, 32, 70,
+97, 100, 101, 32, 40, 112, 111, 115, 105, 195, 167, 195, 163, 111, 32, 100, 111, 32, 99, 114, 111, 115, 115, 102,
+97, 100, 101, 41, 34, 10, 34, 70, 97, 100, 101, 34, 32, 61, 32, 34, 70, 97, 100, 101, 34, 10, 34, 77,
+97, 107, 101, 115, 32, 110, 111, 32, 115, 111, 117, 110, 100, 58, 32, 101, 118, 101, 114, 121, 32, 110, 111, 116,
+101, 32, 105, 116, 32, 103, 101, 116, 115, 32, 112, 108, 97, 121, 115, 32, 105, 116, 115, 32, 99, 104, 105, 108,
+100, 114, 101, 110, 34, 32, 61, 32, 34, 78, 195, 163, 111, 32, 102, 97, 122, 32, 115, 111, 109, 58, 32, 99,
+97, 100, 97, 32, 110, 111, 116, 97, 32, 113, 117, 101, 32, 114, 101, 99, 101, 98, 101, 32, 116, 111, 99, 97,
+32, 111, 115, 32, 102, 105, 108, 104, 111, 115, 34, 10, 34, 67, 104, 105, 108, 100, 114, 101, 110, 34, 32, 61,
+32, 34, 70, 105, 108, 104, 111, 115, 34, 10, 34, 78, 111, 32, 99, 104, 105, 108, 100, 114, 101, 110, 32, 121,
+101, 116, 58, 32, 115, 101, 108, 101, 99, 116, 32, 99, 104, 97, 110, 110, 101, 108, 115, 32, 105, 110, 32, 116,
+104, 101, 32, 67, 104, 97, 110, 110, 101, 108, 32, 82, 97, 99, 107, 44, 32, 116, 104, 101, 110, 32, 112, 114,
+101, 115, 115, 32, 83, 101, 116, 32, 99, 104, 105, 108, 100, 114, 101, 110, 46, 34, 32, 61, 32, 34, 65, 105,
+110, 100, 97, 32, 115, 101, 109, 32, 102, 105, 108, 104, 111, 115, 58, 32, 115, 101, 108, 101, 99, 105, 111, 110,
+101, 32, 99, 97, 110, 97, 105, 115, 32, 110, 111, 32, 67, 104, 97, 110, 110, 101, 108, 32, 82, 97, 99, 107,
+32, 101, 32, 99, 108, 105, 113, 117, 101, 32, 101, 109, 32, 68, 101, 102, 105, 110, 105, 114, 32, 102, 105, 108,
+104, 111, 115, 46, 34, 10, 34, 97, 108, 108, 32, 107, 101, 121, 115, 34, 32, 61, 32, 34, 116, 111, 100, 97,
+115, 32, 97, 115, 32, 116, 101, 99, 108, 97, 115, 34, 10, 34, 82, 101, 109, 111, 118, 101, 32, 102, 114, 111,
+109, 32, 116, 104, 105, 115, 32, 76, 97, 121, 101, 114, 34, 32, 61, 32, 34, 82, 101, 109, 111, 118, 101, 114,
+32, 100, 101, 115, 116, 101, 32, 76, 97, 121, 101, 114, 34, 10, 34, 87, 104, 111, 108, 101, 32, 107, 101, 121,
+98, 111, 97, 114, 100, 32, 102, 111, 114, 32, 116, 104, 105, 115, 32, 99, 104, 105, 108, 100, 34, 32, 61, 32,
+34, 84, 101, 99, 108, 97, 100, 111, 32, 105, 110, 116, 101, 105, 114, 111, 32, 112, 97, 114, 97, 32, 101, 115,
+116, 101, 32, 102, 105, 108, 104, 111, 34, 10, 34, 99, 104, 105, 108, 100, 32, 123, 48, 125, 34, 32, 61, 32,
+34, 102, 105, 108, 104, 111, 32, 123, 48, 125, 34, 10, 34, 83, 112, 108, 105, 116, 32, 99, 104, 105, 108, 100,
+114, 101, 110, 32, 40, 111, 110, 101, 32, 107, 101, 121, 32, 101, 97, 99, 104, 44, 32, 102, 114, 111, 109, 32,
+116, 104, 101, 32, 114, 111, 111, 116, 32, 107, 101, 121, 41, 34, 32, 61, 32, 34, 68, 105, 118, 105, 100, 105,
+114, 32, 102, 105, 108, 104, 111, 115, 32, 40, 117, 109, 97, 32, 116, 101, 99, 108, 97, 32, 99, 97, 100, 97,
+44, 32, 97, 32, 112, 97, 114, 116, 105, 114, 32, 100, 97, 32, 110, 111, 116, 97, 32, 114, 97, 105, 122, 41,
+34, 10, 34, 82, 101, 115, 101, 116, 32, 99, 104, 105, 108, 100, 114, 101, 110, 32, 40, 119, 104, 111, 108, 101,
+32, 107, 101, 121, 98, 111, 97, 114, 100, 44, 32, 114, 111, 111, 116, 32, 111, 110, 32, 67, 53, 41, 34, 32,
+61, 32, 34, 82, 101, 100, 101, 102, 105, 110, 105, 114, 32, 102, 105, 108, 104, 111, 115, 32, 40, 116, 101, 99,
+108, 97, 100, 111, 32, 105, 110, 116, 101, 105, 114, 111, 44, 32, 114, 97, 105, 122, 32, 101, 109, 32, 67, 53,
+41, 34, 10, 34, 71, 114, 111, 117, 112, 32, 99, 104, 105, 108, 100, 114, 101, 110, 46, 46, 46, 34, 32, 61,
+32, 34, 65, 103, 114, 117, 112, 97, 114, 32, 102, 105, 108, 104, 111, 115, 46, 46, 46, 34, 10, 34, 68, 101,
+108, 101, 116, 101, 32, 99, 104, 105, 108, 100, 114, 101, 110, 32, 40, 114, 101, 109, 111, 118, 101, 115, 32, 116,
+104, 101, 32, 99, 104, 97, 110, 110, 101, 108, 115, 41, 34, 32, 61, 32, 34, 69, 120, 99, 108, 117, 105, 114,
+32, 102, 105, 108, 104, 111, 115, 32, 40, 114, 101, 109, 111, 118, 101, 32, 111, 115, 32, 99, 97, 110, 97, 105,
+115, 41, 34, 10, 34, 68, 101, 108, 101, 116, 101, 32, 99, 104, 105, 108, 100, 114, 101, 110, 34, 32, 61, 32,
+34, 69, 120, 99, 108, 117, 105, 114, 32, 102, 105, 108, 104, 111, 115, 34, 10, 34, 68, 101, 108, 101, 116, 101,
+32, 116, 104, 101, 32, 123, 48, 125, 32, 99, 104, 105, 108, 100, 32, 99, 104, 97, 110, 110, 101, 108, 115, 32,
+111, 102, 32, 116, 104, 105, 115, 32, 76, 97, 121, 101, 114, 32, 102, 114, 111, 109, 32, 116, 104, 101, 32, 112,
+114, 111, 106, 101, 99, 116, 63, 34, 32, 61, 32, 34, 69, 120, 99, 108, 117, 105, 114, 32, 100, 111, 32, 112,
+114, 111, 106, 101, 116, 111, 32, 111, 115, 32, 123, 48, 125, 32, 99, 97, 110, 97, 105, 115, 32, 102, 105, 108,
+104, 111, 115, 32, 100, 101, 115, 116, 101, 32, 76, 97, 121, 101, 114, 63, 34, 10,
 };
 } // namespace lynx::i18n::data

+ 407 - 0
src/ui/LayerEditor.cpp

@@ -0,0 +1,407 @@
+#include "ui/LayerEditor.h"
+
+#include <algorithm>
+
+#include "core/Layer.h"
+#include "ui/ControllerKnob.h"
+#include "ui/I18n.h"
+#include "ui/Theme.h"
+#include "ui/ValueControl.h"
+
+namespace lynx
+{
+namespace
+{
+juce::String text (const std::string& s)
+{
+    return juce::String::fromUTF8 (s.c_str());
+}
+
+juce::String keyName (int key)
+{
+    static const char* names[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
+    key = juce::jlimit (0, 127, key);
+    return juce::String (names[key % 12]) + juce::String (key / 12);
+}
+
+juce::Colour childColour (const ChannelDef& c, int index)
+{
+    if (c.colour != 0)
+        return theme::tame (juce::Colour (c.colour));
+    return theme::noteGroupHue (1 + index % 15);
+}
+
+class LayerEditor final : public juce::Component,
+                          private juce::ChangeListener
+{
+public:
+    LayerEditor (AudioEngine& e, int c) : engine (e), channel (c)
+    {
+        auto button = [this] (juce::TextButton& b, const juce::String& title, const juce::String& hint, std::function<void()> click) {
+            b.setButtonText (title);
+            ui::setHint (b, hint);
+            b.onClick = std::move (click);
+            addAndMakeVisible (b);
+        };
+        button (setChildren, tr ("Set children"), tr ("The channels selected in the Channel Rack become this Layer's children (select the ones to keep and press again to remove one)"),
+                [this] {
+                    const auto selected = engine.getSelectedChannels();
+                    engine.editSong ([ch = channel, selected] (Song& s) { layer::setChildren (s, ch, selected); });
+                });
+        button (showChildren, tr ("Show children"), tr ("Selects this Layer's children in the Channel Rack"), [this] {
+            const auto kids = layer::validChildren (engine.getSong(), channel);
+            if (! kids.empty())
+                engine.setChannelSelection (kids, kids.front());
+        });
+        button (menuButton, tr ("Layering") + juce::String::fromUTF8 (" \xe2\x96\xbe"), tr ("Split, reset, group or delete the children"), [this] { showMenu(); });
+
+        auto toggle = [this] (juce::ToggleButton& t, const juce::String& title, const juce::String& hint, std::function<void (LayerSettings&, bool)> set) {
+            t.setButtonText (title);
+            ui::setHint (t, hint);
+            t.onClick = [this, &t, set] {
+                engine.editSong ([ch = channel, on = t.getToggleState(), set] (Song& s) {
+                    if (ch < (int) s.channels.size())
+                        set (s.channels[(std::size_t) ch].layer, on);
+                });
+            };
+            addAndMakeVisible (t);
+        };
+        toggle (random, tr ("Random"), tr ("Random: each note plays one child picked at random (varied hits); off = every child plays"),
+                [] (LayerSettings& l, bool on) {
+                    l.random = on;
+                    if (on)
+                        l.sequential = false;
+                });
+        toggle (sequential, tr ("Sequential"), tr ("Sequential: the children play in turn, one per note (round robin)"), [] (LayerSettings& l, bool on) {
+            l.sequential = on;
+            if (on)
+                l.random = false;
+        });
+        toggle (crossfade, tr ("Crossfade"), tr ("Crossfade: the Fade knob moves from the first child to the last, blending neighbours"),
+                [] (LayerSettings& l, bool on) { l.crossfade = on; });
+
+        auto spec = ui::percentSpec (tr ("Layer - Fade (crossfade position)"), 0.0);
+        spec.toText = [this] (double v) { return fadeText (v); };
+        fade = std::make_unique<ctlui::Knob> (&engine, spec, [this] { return (double) settings().fade; },
+                                              [this] (double v) {
+                                                  engine.editSong ([ch = channel, v] (Song& s) {
+                                                      if (ch < (int) s.channels.size())
+                                                          s.channels[(std::size_t) ch].layer.fade = (float) juce::jlimit (0.0, 1.0, v);
+                                                  });
+                                              });
+        fade->shortName = tr ("Fade");
+        addAndMakeVisible (*fade);
+
+        engine.addChangeListener (this);
+        refresh();
+        setSize (600, 360);
+    }
+
+    ~LayerEditor() override { engine.removeChangeListener (this); }
+
+    void paint (juce::Graphics& g) override
+    {
+        using namespace theme;
+        g.fillAll (colour::bg2);
+        g.setColour (colour::textPrimary);
+        g.setFont (font (type::title, true));
+        g.drawText (tr ("Layer"), 14, 8, 200, 22, juce::Justification::centredLeft);
+        g.setColour (colour::textSecondary);
+        g.setFont (font (type::caption));
+        g.drawText (tr ("Makes no sound: every note it gets plays its children"), 90, 8, getWidth() - 104, 22, juce::Justification::centredRight);
+
+        const auto& song = engine.getSong();
+        const auto kids = layer::validChildren (song, channel);
+        const auto& l = settings();
+
+        // children list
+        auto list = listArea();
+        fillRoundRect (g, list.toFloat(), radius::md, colour::bg0);
+        g.setFont (font (type::caption, true));
+        g.setColour (colour::textSecondary);
+        g.drawText (caps (tr ("Children")) + "  " + juce::String ((int) kids.size()), list.removeFromTop (20).reduced (8, 0), juce::Justification::centredLeft);
+        if (kids.empty())
+        {
+            g.setFont (font (type::small));
+            g.setColour (colour::textDisabled);
+            g.drawFittedText (tr ("No children yet: select channels in the Channel Rack, then press Set children."), list.reduced (10), juce::Justification::centred, 3);
+        }
+        rows.clear();
+        for (int i = 0; i < (int) kids.size() && list.getHeight() >= rowHeight; ++i)
+        {
+            const auto& c = song.channels[(std::size_t) kids[(std::size_t) i]];
+            auto r = list.removeFromTop (rowHeight).reduced (4, 1);
+            rows.push_back ({ r, kids[(std::size_t) i] });
+            const auto selected = engine.getSelectedChannel() == kids[(std::size_t) i];
+            if (selected)
+                fillRoundRect (g, r.toFloat(), radius::sm, colour::accentMuted);
+            else if (r.contains (hoverPoint))
+                fillRoundRect (g, r.toFloat(), radius::sm, colour::bg3);
+            fillRoundRect (g, r.removeFromLeft (6).reduced (0, 3).toFloat(), 2.0f, childColour (c, i));
+            r.removeFromLeft (6);
+            // the crossfade level this child plays at (or full)
+            const auto gain = l.crossfade ? layer::crossfadeGain (i, (int) kids.size(), l.fade) : 1.0f;
+            auto meter = r.removeFromRight (70).reduced (4, 7);
+            fillRoundRect (g, meter.toFloat(), 2.0f, colour::bg4);
+            fillRoundRect (g, meter.withWidth (juce::roundToInt ((float) meter.getWidth() * gain)).toFloat(), 2.0f,
+                           gain > 0.0f ? colour::accent : colour::bg4);
+            auto region = r.removeFromRight (90);
+            g.setFont (font (type::small));
+            g.setColour (c.muted ? colour::textDisabled : colour::textPrimary);
+            g.drawText (text (c.name), r, juce::Justification::centredLeft, true);
+            g.setColour (colour::textSecondary);
+            g.setFont (font (type::caption));
+            g.drawText (! c.hasKeyRegion() ? tr ("all keys")
+                        : c.keyLow == c.keyHigh ? keyName (c.keyLow)
+                                                : keyName (c.keyLow) + juce::String::fromUTF8 ("\xe2\x80\x93") + keyName (c.keyHigh),
+                        region, juce::Justification::centredRight);
+        }
+
+        // keyboard map: the children's key regions over the keys, the Layer's root marked
+        drawKeyMap (g, keyMapArea(), song, kids);
+    }
+
+    void resized() override
+    {
+        auto controls = getLocalBounds().reduced (14).withTrimmedTop (32);
+        controls = controls.removeFromLeft (180);
+        for (auto* b : { &setChildren, &showChildren, &menuButton })
+        {
+            b->setBounds (controls.removeFromTop (28));
+            controls.removeFromTop (6);
+        }
+        controls.removeFromTop (6);
+        for (auto* t : { &random, &sequential, &crossfade })
+        {
+            t->setBounds (controls.removeFromTop (24));
+            controls.removeFromTop (2);
+        }
+        fade->setBounds (controls.removeFromTop (70).withSizeKeepingCentre (70, 70));
+    }
+
+    void mouseMove (const juce::MouseEvent& e) override
+    {
+        hoverPoint = e.getPosition();
+        repaint (listArea());
+    }
+    void mouseExit (const juce::MouseEvent&) override
+    {
+        hoverPoint = { -1, -1 };
+        repaint (listArea());
+    }
+
+    void mouseDown (const juce::MouseEvent& e) override
+    {
+        if (keyMapArea().contains (e.getPosition()))
+        {
+            // right-click a key: the Layer's root (FL's preview keyboard)
+            if (const auto k = keyAt (e.position, keyMapArea()); k >= 0 && e.mods.isPopupMenu())
+                engine.editSong ([ch = channel, k] (Song& s) {
+                    if (ch < (int) s.channels.size())
+                        s.channels[(std::size_t) ch].misc.rootNote = k;
+                });
+            return;
+        }
+        for (const auto& [r, child] : rows)
+            if (r.contains (e.getPosition()))
+            {
+                if (e.mods.isPopupMenu())
+                {
+                    juce::PopupMenu m;
+                    m.addItem (tr ("Remove from this Layer"), [this, child = child] {
+                        engine.editSong ([ch = channel, child] (Song& s) {
+                            auto& kids = s.channels[(std::size_t) ch].layer.children;
+                            kids.erase (std::remove (kids.begin(), kids.end(), child), kids.end());
+                        });
+                    });
+                    m.addItem (tr ("Whole keyboard for this child"), [this, child = child] {
+                        engine.editSong ([child] (Song& s) {
+                            s.channels[(std::size_t) child].keyLow = 0;
+                            s.channels[(std::size_t) child].keyHigh = 127;
+                        });
+                    });
+                    m.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
+                }
+                else
+                    engine.setSelectedChannel (child);
+                return;
+            }
+    }
+
+private:
+    static constexpr int rowHeight = 24;
+
+    const LayerSettings& settings() const
+    {
+        static const LayerSettings none;
+        const auto& song = engine.getSong();
+        return channel >= 0 && channel < (int) song.channels.size() ? song.channels[(std::size_t) channel].layer : none;
+    }
+
+    juce::Rectangle<int> listArea() const { return getLocalBounds().reduced (14).withTrimmedTop (32).withTrimmedLeft (196).withTrimmedBottom (78); }
+    juce::Rectangle<int> keyMapArea() const { return getLocalBounds().reduced (14).removeFromBottom (66); }
+
+    juce::String fadeText (double v) const
+    {
+        const auto n = (int) layer::validChildren (engine.getSong(), channel).size();
+        if (n <= 1)
+            return juce::String (juce::roundToInt (v * 100.0)) + "%";
+        const auto p = v * (n - 1);
+        const auto a = (int) std::floor (p + 1e-9);
+        if (std::abs (p - std::round (p)) < 0.02)
+            return tr ("child {0}", { juce::String ((int) std::round (p) + 1) });
+        return juce::String (a + 1) + "+" + juce::String (a + 2);
+    }
+
+    static bool isBlack (int k) noexcept
+    {
+        const auto n = k % 12;
+        return n == 1 || n == 3 || n == 6 || n == 8 || n == 10;
+    }
+    // the keyboard map shows C1…C10 (12…120): 64 white keys plus the last C
+    static constexpr int firstKey = 12, lastKey = 120;
+    static int whiteIndex (int k) noexcept
+    {
+        int n = 0;
+        for (int i = firstKey; i < k; ++i)
+            n += isBlack (i) ? 0 : 1;
+        return n;
+    }
+    static int whiteCount() noexcept { return whiteIndex (lastKey) + 1; }
+    static juce::Rectangle<float> keyRect (int k, juce::Rectangle<int> area, float keysTop)
+    {
+        const auto w = (float) area.getWidth() / (float) whiteCount();
+        const auto h = (float) area.getBottom() - keysTop;
+        if (isBlack (k))
+            return { (float) area.getX() + (float) whiteIndex (k) * w - w * 0.32f, keysTop, w * 0.64f, h * 0.6f };
+        return { (float) area.getX() + (float) whiteIndex (k) * w, keysTop, w - 1.0f, h };
+    }
+    int keyAt (juce::Point<float> p, juce::Rectangle<int> area) const
+    {
+        const auto keysTop = (float) area.getY() + 26.0f;
+        for (int k = firstKey; k <= lastKey; ++k)
+            if (isBlack (k) && keyRect (k, area, keysTop).contains (p))
+                return k;
+        for (int k = firstKey; k <= lastKey; ++k)
+            if (! isBlack (k) && keyRect (k, area, keysTop).withY ((float) area.getY()).withBottom ((float) area.getBottom()).contains (p))
+                return k;
+        return -1;
+    }
+
+    void drawKeyMap (juce::Graphics& g, juce::Rectangle<int> area, const Song& song, const std::vector<int>& kids) const
+    {
+        using namespace theme;
+        const auto keysTop = (float) area.getY() + 26.0f;
+        const auto root = channel < (int) song.channels.size() ? song.channels[(std::size_t) channel].misc.rootNote : 60;
+        // one lane per child above the keys (up to 4 lanes; more children share them)
+        const auto lanes = juce::jlimit (1, 4, (int) kids.size());
+        const auto laneH = 22.0f / (float) lanes;
+        for (int i = 0; i < (int) kids.size(); ++i)
+        {
+            const auto& c = song.channels[(std::size_t) kids[(std::size_t) i]];
+            const auto lo = juce::jlimit (firstKey, lastKey, c.keyLow), hi = juce::jlimit (firstKey, lastKey, c.keyHigh);
+            const auto x0 = keyRect (lo, area, keysTop).getX(), x1 = keyRect (hi, area, keysTop).getRight();
+            const auto y = (float) area.getY() + (float) (i % lanes) * laneH;
+            fillRoundRect (g, { x0, y + 1.0f, juce::jmax (3.0f, x1 - x0), laneH - 2.0f }, 2.0f, childColour (c, i));
+        }
+        for (int k = firstKey; k <= lastKey; ++k)
+            if (! isBlack (k))
+            {
+                const auto r = keyRect (k, area, keysTop);
+                g.setColour (k == root ? colour::accent : juce::Colour (0xffe6e8ec));
+                g.fillRect (r);
+                if (k % 12 == 0)
+                {
+                    g.setColour (k == root ? colour::onAccent : juce::Colour (0xff5a5f6a));
+                    g.setFont (font (8.5f));
+                    g.drawText ("C" + juce::String (k / 12), r.withTrimmedTop (r.getHeight() - 11.0f).expanded (6.0f, 0.0f).toNearestInt(),
+                                juce::Justification::centred);
+                }
+            }
+        for (int k = firstKey; k <= lastKey; ++k)
+            if (isBlack (k))
+            {
+                g.setColour (k == root ? colour::accent : colour::bg0);
+                g.fillRect (keyRect (k, area, keysTop));
+            }
+    }
+
+    void showMenu()
+    {
+        juce::PopupMenu m;
+        const auto has = ! layer::validChildren (engine.getSong(), channel).empty();
+        m.addItem (tr ("Split children (one key each, from the root key)"), has, false,
+                   [this] { engine.editSong ([ch = channel] (Song& s) { layer::splitChildren (s, ch); }); });
+        m.addItem (tr ("Reset children (whole keyboard, root on C5)"), has, false,
+                   [this] { engine.editSong ([ch = channel] (Song& s) { layer::resetChildren (s, ch); }); });
+        m.addItem (tr ("Group children..."), has, false, [this] { groupChildren(); });
+        m.addItem (tr ("Delete children (removes the channels)"), has, false, [this] {
+            const auto kids = layer::validChildren (engine.getSong(), channel);
+            juce::AlertWindow::showOkCancelBox (juce::MessageBoxIconType::WarningIcon, tr ("Delete children"),
+                                                tr ("Delete the {0} child channels of this Layer from the project?", { juce::String ((int) kids.size()) }),
+                                                tr ("Delete"), tr ("Cancel"), nullptr,
+                                                juce::ModalCallbackFunction::create ([this, kids] (int result) {
+                                                    if (result != 1)
+                                                        return;
+                                                    engine.editSong ([kids] (Song& s) {
+                                                        auto sorted = kids;
+                                                        std::sort (sorted.rbegin(), sorted.rend());
+                                                        for (const auto k : sorted)
+                                                            s.removeChannel (k);
+                                                    });
+                                                }));
+        });
+        m.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&menuButton));
+    }
+
+    void groupChildren()
+    {
+        auto* window = new juce::AlertWindow (tr ("Filter group name"), {}, juce::MessageBoxIconType::NoIcon);
+        const auto& song = engine.getSong();
+        window->addTextEditor ("name", channel < (int) song.channels.size() ? text (song.channels[(std::size_t) channel].name) : tr ("Layer"));
+        window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
+        window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
+        window->enterModalState (true, juce::ModalCallbackFunction::create ([this, window] (int result) {
+                                     const auto name = window->getTextEditorContents ("name").trim().toStdString();
+                                     if (result != 1 || name.empty())
+                                         return;
+                                     engine.editSong ([ch = channel, name] (Song& s) {
+                                         auto it = std::find (s.channelGroups.begin(), s.channelGroups.end(), name);
+                                         const auto group = it != s.channelGroups.end() ? (int) (it - s.channelGroups.begin())
+                                                                                        : (s.channelGroups.push_back (name), (int) s.channelGroups.size() - 1);
+                                         for (const auto k : layer::validChildren (s, ch))
+                                             s.channels[(std::size_t) k].group = group;
+                                         s.channels[(std::size_t) ch].group = group;
+                                     });
+                                 }),
+                                 true);
+    }
+
+    void refresh()
+    {
+        const auto& l = settings();
+        random.setToggleState (l.random, juce::dontSendNotification);
+        sequential.setToggleState (l.sequential, juce::dontSendNotification);
+        crossfade.setToggleState (l.crossfade, juce::dontSendNotification);
+        fade->setEnabled (l.crossfade);
+        fade->setAlpha (l.crossfade ? 1.0f : 0.4f);
+        repaint();
+    }
+
+    void changeListenerCallback (juce::ChangeBroadcaster*) override { refresh(); }
+
+    AudioEngine& engine;
+    int channel;
+    juce::TextButton setChildren, showChildren, menuButton;
+    juce::ToggleButton random, sequential, crossfade;
+    std::unique_ptr<ctlui::Knob> fade;
+    std::vector<std::pair<juce::Rectangle<int>, int>> rows;
+    juce::Point<int> hoverPoint { -1, -1 };
+};
+} // namespace
+
+std::unique_ptr<juce::Component> makeLayerEditor (AudioEngine& engine, int channel)
+{
+    return std::make_unique<LayerEditor> (engine, channel);
+}
+} // namespace lynx

+ 12 - 0
src/ui/LayerEditor.h

@@ -0,0 +1,12 @@
+#pragma once
+
+// The settings page of a Layer channel (round 164, FL's "Layer channel settings" interpreted in LYNX's style): its
+// children, Set / Show children, Random, Crossfade + Fade, Sequential, the Layering menu (Split / Reset / Group /
+// Delete children) and a keyboard map of the children's key regions.
+
+#include "engine/AudioEngine.h"
+
+namespace lynx
+{
+std::unique_ptr<juce::Component> makeLayerEditor (AudioEngine& engine, int channel);
+} // namespace lynx

+ 203 - 0
tests/Layer164Tests.inc

@@ -0,0 +1,203 @@
+// Round 164a: FL's Layer channel (core/Layer.h) and the channels' key region
+
+namespace layer164
+{
+// a hosted "plugin" that records the notes it gets
+struct NoteSpy final : lynx::Instrument
+{
+    struct Got
+    {
+        bool on = true;
+        int key = 0;
+        float velocity = 0.0f;
+    };
+    std::vector<Got> got;
+    void prepare (double) noexcept override {}
+    void noteOn (int key, float velocity) noexcept override { got.push_back ({ true, key, velocity }); }
+    void noteOff (int key) noexcept override { got.push_back ({ false, key, 0.0f }); }
+    void allNotesOff() noexcept override {}
+    void render (float*, float*, int, float, float) noexcept override {}
+    int ons() const
+    {
+        int n = 0;
+        for (const auto& g : got)
+            n += g.on ? 1 : 0;
+        return n;
+    }
+};
+
+struct Rig
+{
+    lynx::Song song;
+    std::vector<std::shared_ptr<NoteSpy>> spies; // [channel] (the Layer's own is unused)
+    std::unique_ptr<const lynx::RackState> state;
+    lynx::RackRenderer renderer;
+    lynx::LiveEventQueue live;
+
+    // channel 0 = the Layer, channels 1…children = spies
+    explicit Rig (int children, std::function<void (lynx::Song&)> setup = {})
+    {
+        song.mixer = lynx::Song::defaultMixer (2);
+        lynx::ChannelDef l;
+        l.name = "Layer";
+        l.instrument = lynx::InstrumentKind::layer;
+        song.channels.push_back (l);
+        for (int k = 0; k < children; ++k)
+        {
+            lynx::ChannelDef c;
+            c.instrument = lynx::InstrumentKind::plugin;
+            c.plugin.id = "spy" + std::to_string (k + 1);
+            song.channels.push_back (c);
+            song.channels[0].layer.children.push_back (k + 1);
+        }
+        song.patterns.emplace_back();
+        if (setup)
+            setup (song);
+        spies.resize (song.channels.size());
+        lynx::RackState::Factories f;
+        f.pluginInstruments = [this] (const lynx::PluginRef& ref, double) {
+            const auto k = std::stoi (ref.id.substr (3));
+            spies[(std::size_t) k] = std::make_shared<NoteSpy>();
+            return std::shared_ptr<lynx::Instrument> (spies[(std::size_t) k]);
+        };
+        state = lynx::RackState::build (song, nullptr, 44100.0, f);
+        renderer.prepare (44100.0, 256);
+    }
+
+    void play (int channel, int key, bool on = true)
+    {
+        lynx::NoteEvent e;
+        e.type = on ? lynx::NoteEvent::Type::on : lynx::NoteEvent::Type::off;
+        e.channel = channel;
+        e.key = key;
+        e.velocity = on ? 0.8f : 0.0f;
+        live.push (e);
+        std::vector<float> l (256), r (256);
+        renderer.process (state.get(), false, 0.0, 256, l.data(), r.data(), &live, nullptr);
+    }
+};
+} // namespace layer164
+
+TEST (layer164_every_child_plays_the_layers_notes)
+{
+    layer164::Rig rig (3);
+    rig.play (0, 60);
+    rig.play (0, 60, false);
+    for (int k = 1; k <= 3; ++k)
+    {
+        CHECK (rig.spies[(std::size_t) k]->ons() == 1);
+        CHECK (rig.spies[(std::size_t) k]->got.size() == 2);
+        CHECK (rig.spies[(std::size_t) k]->got[0].key == 60);
+        CHECK (! rig.spies[(std::size_t) k]->got[1].on);
+    }
+    // a child's own notes don't go to its siblings
+    rig.play (2, 64);
+    CHECK (rig.spies[2]->ons() == 2);
+    CHECK (rig.spies[1]->ons() == 1 && rig.spies[3]->ons() == 1);
+}
+
+TEST (layer164_random_plays_one_child_and_its_off_reaches_it)
+{
+    layer164::Rig rig (4, [] (lynx::Song& s) { s.channels[0].layer.random = true; });
+    std::array<int, 5> count {};
+    for (int n = 0; n < 200; ++n)
+    {
+        rig.play (0, 60);
+        rig.play (0, 60, false);
+    }
+    int total = 0;
+    for (int k = 1; k <= 4; ++k)
+    {
+        count[(std::size_t) k] = rig.spies[(std::size_t) k]->ons();
+        total += count[(std::size_t) k];
+        CHECK (count[(std::size_t) k] > 20); // every child gets picked
+        // each child got as many offs as ons
+        CHECK ((int) rig.spies[(std::size_t) k]->got.size() == 2 * count[(std::size_t) k]);
+    }
+    CHECK (total == 200);
+}
+
+TEST (layer164_sequential_plays_the_children_in_turn)
+{
+    layer164::Rig rig (3, [] (lynx::Song& s) { s.channels[0].layer.sequential = true; });
+    std::vector<int> order;
+    for (int n = 0; n < 6; ++n)
+    {
+        rig.play (0, 60);
+        for (int k = 1; k <= 3; ++k)
+            if (rig.spies[(std::size_t) k]->ons() > (int) std::count (order.begin(), order.end(), k))
+                order.push_back (k);
+        rig.play (0, 60, false);
+    }
+    CHECK (order == std::vector<int> ({ 1, 2, 3, 1, 2, 3 }));
+}
+
+TEST (layer164_crossfade_gains)
+{
+    using lynx::layer::crossfadeGain;
+    // three children: child 1 at 0, 1+2 at 0.25, child 2 at 0.5, 2+3 at 0.75, child 3 at 1
+    CHECK (crossfadeGain (0, 3, 0.0f) == 1.0f && crossfadeGain (1, 3, 0.0f) == 0.0f);
+    CHECK (std::abs (crossfadeGain (1, 3, 0.5f) - 1.0f) < 1e-6f && crossfadeGain (0, 3, 0.5f) == 0.0f && crossfadeGain (2, 3, 0.5f) == 0.0f);
+    CHECK (std::abs (crossfadeGain (0, 3, 0.25f) - crossfadeGain (1, 3, 0.25f)) < 1e-6f);
+    CHECK (crossfadeGain (0, 1, 0.7f) == 1.0f);
+    // a crossfaded Layer only plays the children with a level
+    layer164::Rig rig (3, [] (lynx::Song& s) { s.channels[0].layer.crossfade = true; s.channels[0].layer.fade = 1.0f; });
+    rig.play (0, 60);
+    CHECK (rig.spies[1]->ons() == 0 && rig.spies[2]->ons() == 0 && rig.spies[3]->ons() == 1);
+    // VOL at the default leaves the velocity alone (a plugin has no voice gain: the velocity carries it)
+    CHECK (std::abs (rig.spies[3]->got[0].velocity - 0.8f) < 1e-5f);
+}
+
+TEST (layer164_key_region_and_split_children)
+{
+    layer164::Rig rig (3, [] (lynx::Song& s) {
+        s.channels[0].misc.rootNote = 36;
+        lynx::layer::splitChildren (s, 0);
+    });
+    CHECK (rig.song.channels[1].keyLow == 36 && rig.song.channels[1].keyHigh == 36);
+    CHECK (rig.song.channels[3].keyLow == 38 && rig.song.channels[3].keyHigh == 38);
+    CHECK (rig.song.channels[2].misc.rootNote == 37 && rig.song.channels[2].misc.addToKey);
+    rig.play (0, 37);
+    CHECK (rig.spies[1]->ons() == 0 && rig.spies[2]->ons() == 1 && rig.spies[3]->ons() == 0);
+    // the key region holds for the channel's own notes too
+    rig.play (3, 50);
+    CHECK (rig.spies[3]->ons() == 0);
+    rig.play (3, 38);
+    CHECK (rig.spies[3]->ons() == 1);
+    // reset: the whole keyboard, root back on C5
+    lynx::layer::resetChildren (rig.song, 0);
+    CHECK (rig.song.channels[2].keyLow == 0 && rig.song.channels[2].keyHigh == 127 && rig.song.channels[2].misc.rootNote == 60
+           && ! rig.song.channels[2].misc.addToKey);
+}
+
+TEST (layer164_split_keeps_a_samplers_pitch_on_its_key)
+{
+    lynx::Song s;
+    lynx::ChannelDef l, smp;
+    l.instrument = lynx::InstrumentKind::layer;
+    l.misc.rootNote = 48;
+    smp.instrument = lynx::InstrumentKind::sampler;
+    s.channels = { l, smp, smp };
+    lynx::layer::setChildren (s, 0, { 2, 1, 0, 1, 7 });
+    CHECK (s.channels[0].layer.children == std::vector<int> ({ 1, 2 }));
+    lynx::layer::splitChildren (s, 0);
+    // key 49 plays the second sampler at its own pitch: root 49 → pitch +11 semitones over the C5 default
+    CHECK (s.channels[2].misc.rootNote == 49 && std::abs (s.channels[2].sampler.pitch - 11.0f) < 1e-6f);
+    lynx::layer::resetChildren (s, 0);
+    CHECK (s.channels[2].misc.rootNote == 60 && std::abs (s.channels[2].sampler.pitch) < 1e-6f);
+}
+
+TEST (layer164_children_follow_channel_edits)
+{
+    lynx::Song s;
+    lynx::ChannelDef l, c;
+    l.instrument = lynx::InstrumentKind::layer;
+    s.channels = { c, l, c, c, c };
+    s.channels[1].layer.children = { 0, 2, 4 };
+    s.removeChannel (2);
+    CHECK (s.channels[1].layer.children == std::vector<int> ({ 0, 3 }));
+    CHECK (lynx::layer::parentsOf (s, 3) == std::vector<int> { 1 });
+    lynx::permuteChannels (s, { 3, 0, 1, 2 }); // channel 3 first
+    CHECK (s.channels[2].instrument == lynx::InstrumentKind::layer);
+    CHECK (s.channels[2].layer.children == std::vector<int> ({ 1, 0 }));
+}

+ 2 - 0
tests/tests.cpp

@@ -42,6 +42,7 @@
 #include "core/ProjectContents.h"
 #include "core/FlPatcher.h"
 #include "core/Patcher.h"
+#include "core/Layer.h"
 #include "core/FlSamplers.h"
 #include "core/FlSynths.h"
 #include "core/Inflate.h"
@@ -16045,3 +16046,4 @@ TEST (fl_low_lifter_matches_fl_engine)
 #include "Workflow163Tests.inc"
 #include "Rec163Tests.inc"
 #include "Ui163Tests.inc"
+#include "Layer164Tests.inc"