Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
(feat) Nota Twin — a morphing analog poly (#406)
Egor Khindikaynen28f00e727aba
diff --git a/.claude/launch.json b/.claude/launch.jsonindex 4905b6cd..4d2de1f5 100644--- a/.claude/launch.json+++ b/.claude/launch.json@@ -4,8 +4,27 @@{"name": "nota-docs","runtimeExecutable": "/opt/homebrew/Cellar/node/26.10.0_1/bin/node",- "runtimeArgs": ["../nota-docs/node_modules/astro/bin/astro.mjs", "dev", "--root", "../nota-docs", "--port", "4321"],+ "runtimeArgs": [+ "../nota-docs/node_modules/astro/bin/astro.mjs",+ "dev",+ "--root",+ "../nota-docs",+ "--port",+ "4321"+ ],"port": 4321+ },+ {+ "name": "mockup-311",+ "runtimeExecutable": "/usr/bin/python3",+ "runtimeArgs": [+ "-m",+ "http.server",+ "8311",+ "--directory",+ "/Users/egorkhindikaynen/repos/nota/nota-311"+ ],+ "port": 8311}]-}+}\ No newline at end of filediff --git a/CHANGELOG.md b/CHANGELOG.mdindex c615bfaf..bfa3685f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,40 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.## [Unreleased]### Added+- **Nota Twin — a morphing analog poly** (specs/055): a new built-in instrument with 12 voices.+ Every sound control has a **side A and a side B**, and **Morph** sweeps the whole sound between+ them, including the effects and the depth of each modulation route. The voice has two+ oscillators that run triangle → saw → square continuously, with a Metal folder, sync and FM;+ noise; a Steiner-style multimode filter and a 12 / 24 dB ladder in series or parallel; Brute+ feedback and drive; three envelopes and three LFOs. The card's A / B switch picks the side the+ knobs, automation and MIDI learn write to. Each knob marks the other side and where the sound+ is now. **A → B**, **B → A** and **Swap** are one undo step each.+ - **Expression**: poly aftertouch and MPE (pressure, slide, per-note bend) play one note at a+ time. The expression pad (X · Y · Z) and the mod wheel drive the defaults. Routed to Morph,+ pressure morphs only the pressed note.+ - **Matrix**: a source × destination grid, as on Nota Consort — drag a cell for the depth,+ double-click removes the route. Up to 64 routes per part from 29 sources (LFOs, envelopes,+ velocity, release velocity from a MIDI note-off, key, expression, Pad, Random, 8 macros) to+ Morph, pitch, vibrato or any sound control. A route has a depth per side.+ - **Effects per part**: Mod FX (chorus / flanger / phaser / ensemble), Delay and Reverb, all of+ them morphing. One switch bypasses the section.+ - **Sequencer and arpeggiator**: 8 patterns of up to 64 steps (up to six notes per step,+ velocity, gate or tie), swing, transpose by a held key, latch and step record. With the+ transport stopped a held key plays the pattern (or the arpeggio) at the project tempo;+ with it rolling they keep time with the song. Four motion+ lanes per pattern, recorded or drawn (Morph, the pad or any sound control). **To clip** writes the pattern as a MIDI clip. The+ arpeggiator plays up, down, up / down, random, as played or chord over 1–4 octaves, with hold.+ Patterns travel with presets and projects; every pattern edit is one undo step.+ - **Split and Layer**: two parts, Lower and Upper, each a full Twin sound. They split at a key+ (learnable from a played key) or layer on every key. The 12 voices are shared between the+ parts (2 + 10 … 10 + 2), and each part has its own octave, volume and pan. **Parts** copies+ or swaps them, or loads a factory or saved sound into one part.+ - **117 factory presets** in 11 folders, including Split & Layer and Sequences. The card has+ L and S sizes.+ - **MCP**: `read_twin`, `set_twin_morph_side`, `copy_twin_side`, `copy_twin_part`,+ `set_twin_route`, `get_twin_pattern`, `set_twin_pattern` and `twin_pattern_to_clip`.+- **Preset audition plays a preset's own state**: a Nota Twin preset with a sequence is heard+ playing its pattern.- **Choose the accent colour** (#311): Settings → Appearance → Accent replaces the orange ofeverything live or chosen — the playhead, the loop, selection, toggles that are on, theplay key, menu hover — with one of seven presets (Orange, Lime, Aqua, Sky, Violet,diff --git a/FEATURES.md b/FEATURES.mdindex 81387db9..1156d9ef 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -787,6 +787,25 @@ audio effects after it keep running and keep their settings; saved with the projPoly/Unison/Mono, poly unison stacks, glide, the Release switch, and **Vintage Drift**(seeded per-voice spread — a render is identical for the same seed, so freezing isexact). 40 factory presets. Also builds as a standalone VST3 for other hosts.+- **Nota Twin** — morphing analog poly, 4–12 voices: every sound control has a **side A and a+ side B**, and **Morph** sweeps the whole sound between them, effects and modulation depths+ included. Two oscillators running triangle → saw → square with a Metal folder, sync and FM;+ noise; a Steiner-style multimode filter and a 12 / 24 dB ladder in series or parallel; Brute+ feedback and drive; three envelopes, three LFOs (per voice or global); Poly / Mono / Legato /+ Unison, glide, seeded drift. Poly aftertouch and MPE per note (pressure routed to Morph+ morphs only that note), an X · Y · Z expression pad. A 64-route matrix per part as a source ×+ destination grid (29 sources incl. 8 macros and Random → Morph, pitch, vibrato or any+ control), a depth per side. Per+ part: Mod FX (chorus / flanger / phaser / ensemble), Delay and Reverb. Own sequencer, played from a held key+ or locked to the transport (8 patterns × 64 steps of up to six notes, tie, swing, transpose, latch, step record, four motion+ lanes, **To clip**) and arpeggiator (six modes, 1–4 octaves, hold). **Split / Layer**: Lower+ and Upper parts sharing the voices (2 + 10 … 10 + 2), a learnable split key, per-part octave,+ volume and pan; **Parts** copies, swaps or loads a factory or saved sound into one part. The A / B+ switch picks the side knobs, automation and MIDI learn write to; **A → B**, **B → A**,+ **Swap**. Card tabs Osc, Filter, Env, LFO, Matrix, FX, Seq, Voice; S size shows Morph, the+ pad and four knobs. 117 factory presets in 11 folders; MCP `read_twin`, `set_twin_morph_side`,+ `copy_twin_side`, `copy_twin_part`, `set_twin_route`, `get_twin_pattern`, `set_twin_pattern`,+ `twin_pattern_to_clip`.- **Nota Consort** — paraphonic semi-modular synth: four oscillators (tri / saw / square /pulse, sync 2→1 and 4→3), a mixer with noise, drive and a feedback-normalled EXT input, dualladder filters (HP→LP series, LP/LP or HP/LP parallel stereo with spacing), two ADSRs,@@ -1485,7 +1504,9 @@ Coverage:- **Instruments**: add by kind, read and write parameters (by index or by stable id), turnon or off (`set_device_bypass` with device index -1; `get_overview` shows it), replace withanother built-in or an empty rack (`set_track_instrument`); read / shape Nota Keys in- musical terms (`read_keys`, `set_keys`).+ musical terms (`read_keys`, `set_keys`); Nota Twin's sides, parts, matrix and patterns+ (`read_twin`, `set_twin_morph_side`, `copy_twin_side`, `copy_twin_part`, `set_twin_route`,+ `get_twin_pattern`, `set_twin_pattern`, `twin_pattern_to_clip`).- **Moving devices**: `move_device_to_track` moves or copies an audio effect, a MIDI effect orthe instrument to another track, with its automation.- **Audio effects**: add, remove, reorder, bypass, parameters; load an audio file into adiff --git a/specs/055-morph-poly-synth/checklists/requirements.md b/specs/055-morph-poly-synth/checklists/requirements.mdnew file mode 100644index 00000000..fbc26e3c--- /dev/null+++ b/specs/055-morph-poly-synth/checklists/requirements.md@@ -0,0 +1,36 @@+# Specification Quality Checklist: Nota Twin — a morphing two-filter analog poly++**Purpose**: Validate specification completeness and quality before proceeding to planning+**Created**: 2026-10-30+**Feature**: [spec.md](../spec.md)++## Content Quality++- [x] No implementation details (languages, frameworks, APIs)+- [x] Focused on user value and business needs+- [x] Written for non-technical stakeholders+- [x] All mandatory sections completed++## Requirement Completeness++- [x] No [NEEDS CLARIFICATION] markers remain — resolved 2026-10-30 (see spec § Clarifications)+- [x] Requirements are testable and unambiguous+- [x] Success criteria are measurable+- [x] Success criteria are technology-agnostic (no implementation details)+- [x] All acceptance scenarios are defined+- [x] Edge cases are identified+- [x] Scope is clearly bounded+- [x] Dependencies and assumptions identified++## Feature Readiness++- [x] All functional requirements have clear acceptance criteria+- [x] User scenarios cover primary flows+- [x] Feature meets measurable outcomes defined in Success Criteria+- [x] No implementation details leak into specification++## Notes++- SC-001 names Nota Pentad and the engine perf gate as the yardstick: a project-internal+ reference, not a technology choice — kept deliberately.+- Items marked incomplete require spec updates before `/speckit-clarify` or `/speckit-plan`diff --git a/specs/055-morph-poly-synth/contracts/c-abi.md b/specs/055-morph-poly-synth/contracts/c-abi.mdnew file mode 100644index 00000000..8001a469--- /dev/null+++ b/specs/055-morph-poly-synth/contracts/c-abi.md@@ -0,0 +1,131 @@+# Contract: C ABI and instrument channels (specs/055)++The boundary stays the pure C ABI in `include/nota/nota_engine.h` (AR-7). Twin adds **one**+function; everything else rides existing, instrument-generic entry points (plus the three+generic additions below).++## New++```c+/* Adds an instrument track with the built-in Nota Twin (two-part morphing analog poly,+ * kind 18). id (>0). */+NOTA_API int32_t nota_engine_add_twin_track(NotaEngine* engine);+```++## Added during implementation (beyond the plan)++Not in the original plan; each one closes a requirement the planned surface could not reach.+All are append-only; existing callers are unchanged.++```c+/* A live note-off with its release velocity (0..1), as a MIDI note-off message carries it —+ * engine-wide, and on one track. FR-030: Twin's "Release velocity" matrix source. */+NOTA_API NotaResult nota_engine_note_off_velocity(NotaEngine* engine, int32_t pitch, float release_velocity);+NOTA_API NotaResult nota_track_note_off_velocity(NotaEngine* engine, int32_t track_id, int32_t pitch, float release_velocity);++/* Preset audition: the instrument's state blob after its params (a Twin preset's patterns),+ * so a sequenced preset previews its own pattern (SC-011 presets would otherwise be silent). */+NOTA_API int32_t nota_audition_instrument_state(NotaAudition* rig, const uint8_t* data, int32_t size);++/* Loading a preset onto a Twin already there: the state blob (its patterns), with what it changes+ * in the instrument's edit state as one undo step, so Undo restores the sequence with the sound.+ * Track instrument, an Instrument Rack chain's, and a chain of a rack at a device index. */+NOTA_API int32_t nota_track_instrument_set_state_undoable(NotaEngine* engine, int32_t track_id, const uint8_t* data, int32_t size);+NOTA_API int32_t nota_rack_chain_instrument_set_state_undoable(NotaEngine* engine, int32_t track_id, int32_t chain, const uint8_t* data, int32_t size);+NOTA_API int32_t nota_rackdev_chain_instrument_set_state_undoable(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, const uint8_t* data, int32_t size);++/* A rack chain instrument's params have no undo target: after a batch of param writes (a Twin+ * side / part copy, a preset), the state read before them becomes one undo step that swaps the+ * whole state (MixKind::InstrumentState, 10). The rack-chain proxy calls it around each mix+ * gesture on the chain instrument's params. */+NOTA_API int32_t nota_rack_chain_instrument_record_state_undo(NotaEngine* engine, int32_t track_id, int32_t chain, const uint8_t* before, int32_t size);+NOTA_API int32_t nota_rackdev_chain_instrument_record_state_undo(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, const uint8_t* before, int32_t size);+```++Inside the engine (no ABI):++- `Instrument::noteOffVelocity(pitch, velocity)`: a note-off that carries its release velocity.+ It defaults to `noteOff`, so other instruments are unaffected. MIDI input sends it for a+ 0x80 message, and an Instrument Rack passes it on to its plain chains. A note-on at velocity+ 0 and clip notes (which store no release velocity) still send a plain note-off.+- `Delay::A_Reset` and `Reverb::A_Reset` (`deviceAction` id 1 on each): the device starts over+ as a new one. This clears the tail, the modulation / wow phase and the time / size glide.+ Twin's built-in effects use it on a silent start, so a second render, a freeze and a render+ at another rate match the first one exactly (SC-008, edge cases). `A_KillTail` /+ `A_ClearLoop` keep their old, narrower meaning.+- The undo step for an edit-state change (`MixKind::InstrumentEdit`, 9 — develop took 8 for+ `TrackSend`) also covers a Twin in a rack chain: `deviceIndex` is the rack, `paramIndex` the+ chain (−1 = the track's own instrument). `nota_rack_chain_instrument_action` records it too.+- Inside an open undo group, edit-state changes of one instrument fold into one entry (so a+ 64-step pattern write can't push the group's start out of the 128-step history), and the saved+ states only the undo / redo history refers to are reclaimed (`Engine::compactNoteStates`).+- The engine's sustain pedal keeps each held key's release velocity (`Instrument::pedalRelVel`)+ and sends it with the note-off when the pedal comes up.++## Reused (no signature change)++| Need | Entry point |+|------|-------------|+| Params (both sides, both parts, matrix, sequencer settings) | the plugin-param family used by every built-in (count / id / name / get / set / text / default), `deviceIndex = -1` |+| Automation, MIDI learn, macros, CV links | existing param targets — Twin's params are ordinary targets |+| Pattern editing | `nota_track_instrument_action(engine, track, id, iarg, farg)` (and the rack-chain twin `nota_rack_chain_instrument_action`) — action ids below |+| Pattern read-back | the instrument state read (`nota_device_get_state`, device −1; chain variant for racks) |+| Live telemetry | the instrument scope read (`scopeRead`) — layout below |+| Voice meter, held notes | `activeVoiceCount`, `heldNotes` |+| Replace / clone / freeze / rack | engine factory by kind 18 |++## `action()` ids (append-only)++| Id | Name | iarg | farg |+|----|------|------|------|+| 0 | `SelectPattern` (edit target) | pattern 0..7 | — |+| 1 | `SetLength` | steps 1..64 | — |+| 2 | `ClearStep` | step | — |+| 3 | `AddStepNote` | step << 8 \| note | velocity 0..1 |+| 4 | `RemoveStepNote` | step << 8 \| note | — |+| 5 | `SetStepVelocity` | step | 0..1 |+| 6 | `SetStepGate` | step | 0..1 (> 1 = tie) |+| 7 | `StepRecordArm` | 0 / 1 | — |+| 8 | `StepRecordAdvance` | — | — (rest step) |+| 9 | `ClearPattern` | pattern | — |+| 10 | `CopyPattern` | from << 8 \| to | — |+| 11 | `MotionTarget` | lane << 16 \| param index (0xFFFF none) | — |+| 12 | `MotionMode` | lane | 0 stepped / 1 smooth |+| 13 | `MotionSet` | lane << 8 \| step | value 0..1, < 0 = unset |+| 14 | `MotionRecordArm` | lane (−1 off) | — |+| 15 | `ClearMotion` | lane | — |+| 16 | `StepRecordPoll` | — | — (the card's tick: notes played while armed become steps) |++Every edit bumps the pattern revision and publishes a new immutable pattern snapshot (AR-5).+An edit that changes the patterns is one undo step: the engine records the instrument's edit+state (`Instrument::editState`, a new `MixKind::InstrumentEdit`) around `instrumentAction`, and+undo hands the old bytes back without republishing the instrument, so sounding notes go on.+Side / part copies (A → B, swap, copy part) are **not** actions: the app writes the params in+one mix gesture (research R14), so they are ordinary undoable param edits.++## `scopeRead` layout (append-only)++| Index | Value |+|-------|-------|+| 0 | playing step (−1 stopped) |+| 1 | playing pattern |+| 2 | pending pattern (−1 none) |+| 3 | pattern revision |+| 4 | sounding voices Lower |+| 5 | sounding voices Upper |+| 6 | Lower live morph (part, before per-voice) |+| 7 | Upper live morph |+| 8–19 | per-voice morph (12 voices; −1 idle) |+| 20–22 | LFO 1–3 phase output (Lower), for the card's LFO graphs |+| 23 | output peak (dBFS) |+| 24 | step-record cursor (−1 = not recording) |+| 25 | last key played, MIDI 0..127 (−1 = none) — the card's split-point learn |++## Behavioural contract checked by the smoke test++1. `nota_engine_add_twin_track` returns a track that renders a non-silent Init note.+2. Morph = 0 / 1 render equals a patch whose B / A side was copied from A / B (SC-002).+3. Per-note pressure on one note of a chord leaves the others' render unchanged (SC-005).+4. A 16-step pattern started by the transport fires on the grid at 90 and 174 BPM (SC-009).+5. `get_state` → new instance `set_state` → identical render (SC-008); a truncated param+ array and a missing pattern block still load (FR-052).diff --git a/specs/055-morph-poly-synth/contracts/mcp-tools.md b/specs/055-morph-poly-synth/contracts/mcp-tools.mdnew file mode 100644index 00000000..64d2d562--- /dev/null+++ b/specs/055-morph-poly-synth/contracts/mcp-tools.md@@ -0,0 +1,22 @@+# Contract: MCP surface (specs/055)++FR-054: at least what other built-ins have. Generic tools already cover Twin once kind 18 is in+`InstrumentTools`' kind list: `list_instrument_kinds`, `add_instrument_track` /+`set_track_instrument` (kind 18), `get_instrument_params`, `set_instrument_param`,+`set_instrument_param_by_id` (ids per [data-model.md](../data-model.md)), preset load.++Twin-specific tools (shaped like `read_pendulum` / `set_pendulum`, `get_rhythm` /+`set_rhythm_pattern`):++| Tool | Input | Output / effect |+|------|-------|-----------------|+| `read_twin` | track id, part (`lo` default / `up`) | layout (Single / Layer / Split), split key, voice share, the part the sequencer plays; for the part read: morph, voice mode, edited-side-independent summary of A and B for the main controls, used matrix routes `(slot, src, dst, amtA, amtB)` by name |+| `set_twin_morph_side` | track, part, side, `{id: value}` | sets params on one side; one undo step |+| `copy_twin_side` | track, part, `a_to_b` / `b_to_a` / `swap` | one undo step |+| `copy_twin_part` | track, `lower_to_upper` / `upper_to_lower` / `swap` | the whole part (both sides, matrix, FX, voice settings); one undo step |+| `set_twin_route` | track, part, slot (or `next_free`), src name, dst name, amtA, amtB | errors "matrix full" when no slot is free |+| `get_twin_pattern` | track, pattern | steps as text rows (`C3 E3 G3:100:50%`, `.` rest, `~` tie) + motion lanes |+| `set_twin_pattern` | track, pattern, rows | replaces the pattern; one undo step |+| `twin_pattern_to_clip` | track, pattern, start bar | creates the MIDI clip (+ automation for motion lanes), returns clip id |++One MCP call = one undo step (specs/016 rule).diff --git a/specs/055-morph-poly-synth/data-model.md b/specs/055-morph-poly-synth/data-model.mdnew file mode 100644index 00000000..ef91417a--- /dev/null+++ b/specs/055-morph-poly-synth/data-model.md@@ -0,0 +1,96 @@+# Data model: Nota Twin (specs/055)++All sound data are normalized plugin-params (0..1, stable string ids, append-only order). Only+the sequencer patterns live in the state blob. Display names read `<Part> <Side> · <Group> <Leaf>`+("Lower A · Ladder Cutoff", "Upper · Morph", "Patch Mode"): the automation menu groups params+on the part of the name before its last space, so each section becomes one submenu. See [research.md](research.md) R2, R9, R10.++## Patch (the instrument)++| Field | Param id | Values | Notes |+|-------|----------|--------|-------|+| Mode | `mode` | Single / Layer / Split | stepped; changing releases, never cuts |+| Split key | `splitkey` | MIDI 0..127 | Split only; first key of Upper |+| Voice share | `share` | Lower 2..10 (step 2) | Upper = 12 − Lower; Single → all 12 to Lower |+| Max voices | `voices` | 4..12 | CPU cap (FR-001) |+| Expression pad | `padx`, `pady`, `padz` | 0..1 | side- and part-less, automatable (FR-031) |+| Bend range | `bendrange` | ±2 / ±5 / ±12 / ±24 | MPE controllers' announced range wins per note |+| Edit side / part | — | view state | card only, not a param, not saved in presets |+| Parts | `lo.*`, `up.*` | Part | Upper is present but silent in Single |+| Sequencer settings | `seq.*` | see Pattern | global |+| Patterns | state blob | Pattern × 8 | structural, R10 |++## Part (`lo` / `up`)++Side-less per part: `morph`, `voicemode` (Poly / Mono / Legato / Unison), `glide`,+`glidelegato`, `octave` (Split transpose), `vol`, `pan`, `fxon` (whole section bypass), the 64+matrix slots' `mN.src` / `mN.dst`, 8 macro values `macroN` and macro target slots.++Per side (`<part>.a.*` and `<part>.b.*`) — the morphed sound:++| Group | Params |+|-------|--------|+| Osc 1 / Osc 2 | `oNwave`, `oNpw`, `oNmetal`, `oNcoarse`, `oNfine`, `oNlevel`, `oNbal` (filter balance) |+| Osc links | `sync` (stepped), `fm21` (Osc 2 → Osc 1), `fmfilt` (osc → multimode cutoff), `o2lo` (stepped, low-freq / kbd-off) |+| Noise | `noiselevel`, `noisecolor`, `noisebal` |+| Multimode | `mmcut`, `mmres`, `mmmode`, `mmkey`, `mmenv` |+| Ladder | `ldcut`, `ldres`, `ldslope` (stepped 12/24), `ldkey`, `ldenv` |+| Routing / drive | `route` (series ↔ parallel), `brute`, `drive` |+| Envelopes | `fenv{a,d,s,r,vel,curve}`, `aenv{a,d,s,r,vel,curve}`, `menv{dly,a,d,s,r,vel,loop}` |+| LFO 1–3 | `lfoN{shape,rate,sync,syncdiv,mode(voice/global),retrig,fade,amt}`; LFO 3 + `lfo3sym`, `lfo3curve` |+| Hard-wired | `vibamt` (LFO 1 → pitch, mod-wheel scaled); velocity → amp is the amp envelope's `aenvvel` |+| Drift / stereo | `drift`, `unidetune`, `spread`, `spreadmode` (stepped) |+| Matrix depth | `mNamt` for N = 1..64 |+| FX | `modfx{type,rate,depth,mix}`, `dly{time,sync,div,fb,pingpong,mix}`, `rev{size,damp,mix}`, `modfxon`, `dlyon`, `revon` |++**Morph rule** (R3): continuous → interpolated in the param's musical domain; stepped (marked+above) → A below 0.5, B from 0.5. Morph = 0 / 1 reproduce A / B exactly.++**Validation**: `share` snaps to even values; `splitkey` 0..127; matrix `dst` that is a stepped+param is rejected by the card (stepped params aren't destinations); a slot with `src = none`+or `dst = none` is empty.++## Modulation route (matrix slot)++`(src, dst, amtA, amtB)` per slot, 64 per part. Sources (append-only table): none, LFO 1–3,+filter env, amp env, mod env, velocity, release velocity, key, pressure (per note, falls back+to channel AT), slide, per-note bend, mod wheel, pitch wheel, pad X / Y / Z, random-per-note,+macro 1–8, sequencer gate / step value. Destinations (append-only): every continuous voice or+part param of the table above, plus `morph` (evaluated per voice when the source is per-note).++## Voice expression state (audio thread only)++Per voice: note, velocity, release velocity, pressure, slide, bend, random seed, the part it+belongs to, its own morph value (part morph + per-voice matrix contribution, clamped 0..1).++## Pattern (state blob, 8 per patch)++| Field | Range |+|-------|-------|+| length | 1..64 steps |+| step[i].notes | 0..6 MIDI notes (0 = rest) |+| step[i].velocity | 1..127 |+| step[i].gate | 1..100 % of step, or tie |+| motion[0..3].target | param index or none |+| motion[k].mode | stepped / smooth |+| motion[k].value[i] | 0..1 or "unset" (no override on that step) |++Global sequencer params: `seq.on`, `seq.kind` (Seq / Arp), `seq.pattern` (1..8, switches at+pattern end), `seq.rate`, `seq.swing`, `seq.latch`, `seq.transpose` (on/off), `seq.target`+(Lower / Upper / Both), `arp.mode`, `arp.oct`, `arp.gate`, `arp.hold`.++**State transitions** (sequencer): `Stopped` → (transport rolls ∧ `seq.on`) → `Running` →+(transport stops ∨ `seq.on` off) → `Stopped` (releases its notes). A transport jump while+`Running` → re-align at next step (releases sounding notes). Pattern switch request → `Pending`+→ applied at the current pattern's end.++## State blob layout++`[u32 magic "TWN1"] [u32 paramCount] [paramCount × f32 LE] [u32 patternBytes] [pattern data]`+— `setState` tolerates shorter / longer param arrays and a missing pattern block (FR-052).+The preset `StateBase64` carries only the pattern block (params travel as `NamedParams`, R11).++## Factory preset++`Inst("twin", 18, name, params…, TwinSeq(...)?)` in `FactoryPresetCatalog`, folder, macro+names; ≥ 40 (US6), ≥ 8 with sequencer / arp, ≥ 6 Split / Layer (SC-011).diff --git a/specs/055-morph-poly-synth/design/handoff.md b/specs/055-morph-poly-synth/design/handoff.mdnew file mode 100644index 00000000..ed44053f--- /dev/null+++ b/specs/055-morph-poly-synth/design/handoff.md@@ -0,0 +1,81 @@+<!-- SPDX-License-Identifier: AGPL-3.0-only -->+<!-- Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms. -->++# Nota Twin card — design handoff++The visual reference is [`twin-card.html`](twin-card.html). Open it in a browser. The card in it+is live: tabs, A / B, Single / Layer / Split, S / L, the morph demo, the delay on/off state, the+theme (Studio Dark / Light), and knobs you can drag. At 1× scale, one CSS px is one Avalonia+logical px. Token values in it come from `Theme/Themes/studio-*.json`. If the HTML and a theme+file disagree, the theme file is right.++Scope: `src/managed/Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs` and+`Controls/TwinViews.cs`. No engine or parameter changes. Every control drives the same param id it+drives now.++## Frame++| Part | Now | Target |+|---|---|---|+| Card | 700 × 260, S 260 | unchanged |+| Status line | 18 px at the bottom | **removed**. It repeated the header badge and the side switch. Its 18 px go to `BodyH`. |+| Morph column | 64, Morph knob 40, A/B, three raised buttons | 70 (64 + Rule). Morph `KnobMain` 44, value mono 9, **morph strip** 56 × 3 with `A` and `B` at its ends (the end being edited takes the accent), “Edit” A / B segments (fill, 18 tall), A → B / B → A / Swap as **ghost** buttons 56 × 16 |+| Tab row | 20, tabs + Parts + Single/Layer/Split (clipped) | 22, Rule under it. Tabs 10.5/600, padding 7; the chosen tab gets Ink 0 and a 2 px accent underline. Right side: Lower / Upper (only when the layout is Layer or Split), then Single / Layer / Split, both 18 tall. **“Parts” button removed** |+| Tab body | ~186, content top-aligned, bottom 40 % empty | 612 × 204. Sections via `DeviceCardKit.Section` (padding 5/8, gap 4), each with a 16 px header row. The header row carries the section's switch or chooser on its right |+| Section chevrons “›” | between every island | **removed**. The Rule alone divides sections |++**Row rule.** Sections that sit side by side use the same row order: header 16, then graph or+chooser, then a knob row (53 tall for a 34 knob, 62 for a 44 knob), then a second knob row, then+slider rows of 14. This keeps knob rows on a shared baseline across the tab.++## Per tab++| Tab | Changes |+|---|---|+| **Osc** | Osc 1 212 · Osc 2 212 · Noise rest. Each source gets a full-width wave graph (196 × 34, `TwinWaveView`) where the 56 × 16 thumbnail was. Row 1: Wave, Width, Metal, Level. Row 2: Coarse, Fine (+ FM 1, FM cut in teal on Osc 2). `o*bal` / `noisebal` become a **slider row “To filter”** with end words *multi … ladder* (it was a knob reading “Filter · ladder”). Noise gets a small colour-tilt graph |+| **Filter** | Multimode 144 · Route 132 · Ladder 144 · Response rest. `mmmode` is continuous: it becomes a **slider with four marks** LP · BP · HP · notch. Cutoff and Resonance are 44 in both filters; Key and Env are 34 teal. Route: `route` becomes a series ↔ parallel slider plus a **route diagram** (new read-only view, 116 × 62), then Brute and Drive. Ladder: 12 / 24 in the header. Response 176 × 172: combined curve in `VizInk`, multimode `Teal`, ladder `Steel`, the active node in accent |+| **Env** | Three equal sections, 204 each. Graph 186 × 70. Under it, **four `DragNumber` cells** labelled Attack / Decay / Sustain / Release, replacing the unlabelled “1 ms · 91 ms · 50 % · 39 ms” string. Then Velocity (teal) + Curve, or Delay + Velocity on Mod env. Loop stays in the Mod env header |+| **LFO** | LFO 500 · Vibrato rest. LFO 1 / 2 / 3 moves into the section header. Left column (206): shape segments full width; then Sync, Retrig and Voice / Global on one row; then Rate (Division while synced), Fade and Amount (teal) as 44 knobs. LFO 3 adds Symmetry and Curve to that row at 34. Graph 258 × 166 with the live phase line. Vibrato: Depth 44 teal, caption “LFO 1 × mod wheel” |+| **Matrix** | Matrix 412 · Macros rest. *Changed 2026-11-06:* a source × destination grid as on Nota Consort (`TwinPatchMatrix`): header `n / 64` (and "k routes off the grid"), row names 72 wide, 6 × 5 cells (up to 8 × 6 when the routes need it), a cell shows the edited side's depth with the other side as a tick; drag sets the depth, double-click removes, a name opens the source / destination menu. Macros: 2 × 4 knobs, plus a one-line hint |+| **FX** | Mod FX 178 · Delay 178 · Reverb 178 · All rest. Each effect gets a 162 × 40 read-only preview (sweep · taps L/R · tail) and 44 knobs. **An effect that is off puts its body in `Inactive`**, so its Sync / Ping-pong switches stop showing the accent. The old “Section · Effects” column becomes **All** with a switch and the hint “Off bypasses all three, to use Nota's effect devices instead.” |+| **Seq** | Header: Plays (Layer/Split only), Record, To clip, On, Seq / Arp. Toolbar: Pattern 1–8, Length, Rate, Swing, Transpose, Latch. Step grid 594 × 78: chords, a velocity foot, the playing step in `AccentSubtle`, the selected step with an accent outline. Motion row: lane 1–4, target dropdown, Smooth, Arm, Clear, then Steps pages on the right. Motion lane 594 × 26 in teal. Last row: the selected step readout, Rest, Tie, and the hint that used to sit in the status line. **Arp:** Mode, Rate, Octaves, Hold on one row; arp preview graph 420 × 120; Gate and Swing at 44 |+| **Voice** | Voices 200 · Stereo 132 (118 in Layer/Split) · Output 140 / Part 160 · Pad rest. The voice mode chooser moves into the Voices header. **Detune is `Inactive` outside Unison**, with a hint saying why. Stereo: Spread, Drift at 44, then “Spread by” segments. Output: Volume, Pan at 44, then **Bend range as segments** ±2 · ±5 · ±12 · ±24 (`bendrange` has 4 steps; it used to be a knob). In Layer / Split this column becomes **Lower part / Upper part**: Volume, Pan, Octave, then Split key + Learn (Split only), Voices share, Bend. Pad 118 × 108 with the X / Y / Z readout and the legend “X cutoff · Y morph · Z vibrato” |+| **S size** | Morph column (no copy actions) · pad 172 × 124 · Cutoff, Reso, Attack, Release in a row |++## New or extended pieces++1. `DeviceCardKit.SliderRow` overload: end words or N marks under the track, with an optional+ hidden label and value. Used for To filter, Route and Mode.+2. `TwinViews.cs`: `TwinRouteView` (series/parallel diagram), `TwinDepthBar` (matrix depth),+ and three read-only previews `TwinModFxView`, `TwinDelayView`, `TwinReverbView`. All of them go+ through `NotaGraph`: well, Rule frame, radius 3, curves in `VizInk`, no fills under curves.+3. A morph strip with A/B end labels (extends `TwinMorphStrip`).+4. ADSR `DragNumber` cells in a 4-column grid (an existing control used in a new layout).++## Unchanged++- Param ids, ranges and formatters (`Attack`, `Cutoff`, `Wave` …).+- The knob's other-side tick and the morph dot that shows where the sound is now.+- The header from `BuildCardShell`: name · preset · badge · S/L · power.+- Interaction contract: vertical drag, Shift for fine steps, double-click resets, left button only,+ automation gestures, MIDI Learn.++## As built (2026-10-31)++Implemented in `TwinInstrumentCard.cs` and `TwinViews.cs`. In four places the build differs from the mockup:++- **Parts menu.** The menu still exists. It holds copy and swap of the parts and *Load into Lower / Upper*, which also turns a Single patch into Layer. It is now a button in the header of Voice → Output (Part).+- **Motion lane.** Motion values are still drawn as teal ticks inside the step grid, not in a separate strip. The grid is taller (92 px) to give them room.+- **Arp preview.** No arp preview graph was built. The arp page has the mode row, Gate and Swing at 44, and a hint.+- **Filter graph colour.** The ladder curve stays rose (`TwinFilterView`), as before, not blue.++The matrix depth uses the existing `SliderTrack` in bipolar, teal mode. The other side's depth is shown as its `Marker`. Kit additions: `SliderRow(…, withTrack:)` and `DeviceCardKit.SliderMarks`.++## Checks++- [ ] `scripts/build.sh` passes, including `DesignTokenCheck` (`RunStudio`, `RunLabels`, `RunIcons`).+- [ ] Nothing is clipped at 700 in Single, Layer or Split (tab row, Voices header, Seq toolbar).+- [ ] With side B being edited, B is the only accent in the morph column; at morph 35 % the knobs show the “now” dot.+- [ ] With Delay off, nothing inside the Delay section is orange.+- [ ] Every tab in all four themes: Studio Dark, Studio Light, Ember Graphite, Ember Paper.+- [ ] Re-shoot the docs screenshots of the card (`nota-docs`).diff --git a/specs/055-morph-poly-synth/design/twin-card.html b/specs/055-morph-poly-synth/design/twin-card.htmlnew file mode 100644index 00000000..f95fd732--- /dev/null+++ b/specs/055-morph-poly-synth/design/twin-card.html@@ -0,0 +1,716 @@+<!DOCTYPE html>+<!-- SPDX-License-Identifier: AGPL-3.0-only -->+<!-- Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms. -->+<html lang="en">+<head>+<meta charset="utf-8">+<title>Nota Twin — device card design (specs/055)</title>+<style>+@font-face { font-family: Geist; src: url(../../../src/web/remote/public/fonts/Geist-Regular.woff2) format("woff2"); font-weight: 400 500; }+@font-face { font-family: Geist; src: url(../../../src/web/remote/public/fonts/Geist-SemiBold.woff2) format("woff2"); font-weight: 600 700; }+@font-face { font-family: "Geist Mono"; src: url(../../../src/web/remote/public/fonts/GeistMono-Medium.woff2) format("woff2"); }++/* Token values copied from src/managed/Nota.App/Theme/Themes/studio-*.json (the theme files win). */+:root, .t-dark {+ --SurfaceAbyss:#17181A; --BgApp:#1E1F22; --BgSunken:#17181A; --Panel:#2B2D31; --SurfaceRaised:#34363B; --SurfaceHover:#393C41;+ --Seam:#141517; --Rule:#45484E; --VizGrid:#2E2F32;+ --TextHeading:#F4F5F6; --TextPrimary:#E8E9EB; --TextSecondary:#C0C4C9; --TextMuted:#A4A9B0; --TextTertiary:#92969D;+ --TextFaint:#82868C; --TextDisabled:#82868C; --TextAxis:#82868C; --TextOnAccent:#17181A;+ --VizInk:#D7D8DA; --Accent:#FF9F1C; --AccentHover:#FFB547; --AccentSubtle:#4D3F2E;+ --Teal:#5FB3A8; --Rose:#D77A8F; --Steel:#6A9FD8; --Record:#F06A6E;+ --ShadowBevel:#FFFFFF12;+}+.t-light {+ --SurfaceAbyss:#D6D8DB; --BgApp:#C9CBCF; --BgSunken:#D6D8DB; --Panel:#E4E5E7; --SurfaceRaised:#EEEFF1; --SurfaceHover:#F7F8F9;+ --Seam:#9DA0A6; --Rule:#B3B6BB; --VizGrid:#C0C3C6;+ --TextHeading:#0E0F11; --TextPrimary:#16171A; --TextSecondary:#3A3D42; --TextMuted:#4F535A; --TextTertiary:#65696F;+ --TextFaint:#797C81; --TextDisabled:#797C81; --TextAxis:#797C81; --TextOnAccent:#17181A;+ --VizInk:#252629; --Accent:#EF8A0C; --AccentHover:#C46A00; --AccentSubtle:#E6D6C4;+ --Teal:#3A8A7F; --Rose:#B4566B; --Steel:#3F78B8; --Record:#B3262C;+ --ShadowBevel:#FFFFFFB3;+}++* { box-sizing: border-box; }+body { margin: 0; background: var(--BgApp); color: var(--TextPrimary); font: 400 13px/1.45 Geist, system-ui, sans-serif; }+.page { max-width: 1520px; margin: 0 auto; padding: 28px 32px 80px; }+h1 { font-size: 20px; font-weight: 600; margin: 0 0 4px; color: var(--TextHeading); }+h2 { font-size: 15px; font-weight: 600; margin: 36px 0 10px; color: var(--TextHeading); }+h3 { font-size: 13px; font-weight: 600; margin: 18px 0 6px; color: var(--TextHeading); }+p, li { color: var(--TextSecondary); max-width: 980px; }+code { font: 12px "Geist Mono", ui-monospace, monospace; color: var(--TextPrimary); }+.lede { color: var(--TextMuted); margin: 0 0 18px; }+table.spec { border-collapse: collapse; margin: 6px 0 14px; font-size: 12px; }+table.spec td, table.spec th { border-top: 1px solid var(--Rule); padding: 5px 14px 5px 0; vertical-align: top; text-align: left; color: var(--TextSecondary); }+table.spec th { color: var(--TextMuted); font-weight: 600; }+table.spec td:first-child { color: var(--TextPrimary); white-space: nowrap; }++/* toolbar of the page (not part of the design) */+.bar { display: flex; gap: 18px; align-items: center; flex-wrap: wrap; margin: 0 0 18px; font-size: 12px; color: var(--TextMuted); }+.bar .pg { display: inline-flex; border: 1px solid var(--Seam); border-radius: 3px; overflow: hidden; }+.bar .pg button { font: 500 12px Geist, sans-serif; background: var(--SurfaceRaised); color: var(--TextSecondary); border: 0; border-left: 1px solid var(--Seam); padding: 4px 10px; cursor: pointer; }+.bar .pg button:first-child { border-left: 0; }+.bar .pg button.on { background: var(--Accent); color: var(--TextOnAccent); }+.stage { display: flex; gap: 24px; align-items: flex-start; flex-wrap: wrap; }+.zoomwrap { zoom: 2; }+.caption { font-size: 12px; color: var(--TextMuted); margin: 8px 0 0; }++/* ===================== the card (true size, 1 px = 1 logical px) ===================== */+.card { width: 700px; height: 260px; background: var(--Panel); border: 1px solid var(--Seam); border-radius: 3px; overflow: hidden;+ display: flex; flex-direction: column; user-select: none; font-family: Geist, system-ui, sans-serif; color: var(--TextPrimary); position: relative; }+.card.mini { width: 260px; }+.hdr { height: 22px; flex: none; display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; padding: 0 6px 0 8px;+ background: var(--SurfaceRaised); border-bottom: 1px solid var(--Seam); box-shadow: inset 0 1px 0 var(--ShadowBevel); }+.hdr .nm { font-size: 12px; font-weight: 600; color: var(--TextHeading); white-space: nowrap; }+.hdr .rt { display: flex; justify-content: flex-end; align-items: center; gap: 6px; }+.badge { font: 10px "Geist Mono", monospace; color: var(--TextMuted); white-space: nowrap; }+.preset { height: 18px; display: flex; align-items: stretch; background: var(--BgSunken); border: 1px solid var(--Rule); border-radius: 3px; font-size: 11px; font-weight: 500; }+.preset span { display: flex; align-items: center; padding: 0 6px; color: var(--TextMuted); }+.preset .pn { min-width: 132px; border-left: 1px solid var(--Rule); border-right: 1px solid var(--Rule); color: var(--TextPrimary); justify-content: space-between; gap: 8px; }+.body { flex: 1; display: flex; padding: 6px; min-height: 0; }++/* morph column */+.morph { width: 70px; flex: none; display: flex; flex-direction: column; align-items: center; padding: 2px 6px 0 0; border-right: 1px solid var(--Rule); margin-right: 0; }+.sect-t { font-size: 10.5px; font-weight: 600; color: var(--TextMuted); line-height: 14px; white-space: nowrap; }+.mstrip { width: 56px; display: grid; grid-template-columns: 7px 1fr 7px; align-items: center; gap: 3px; margin: 3px 0 0; font: 8px "Geist Mono", monospace; color: var(--TextFaint); }+.mstrip .tr { height: 3px; background: var(--BgSunken); border-radius: 2px; position: relative; box-shadow: 0 0 0 1px var(--Rule) inset; }+.mstrip .tr i { position: absolute; top: -2px; width: 3px; height: 7px; margin-left: -1.5px; background: var(--VizInk); border-radius: 1px; }+.mstrip b.on { color: var(--Accent); font-weight: 400; }+.cap { font-size: 8px; font-weight: 500; color: var(--TextMuted); line-height: 11px; }+.ghost { height: 16px; width: 56px; display: flex; align-items: center; justify-content: center; font-size: 9px; font-weight: 500; color: var(--TextSecondary);+ border-radius: 2px; cursor: default; }+.ghost:hover { background: var(--SurfaceHover); color: var(--TextPrimary); }++/* main area */+.main { flex: 1; display: flex; flex-direction: column; min-width: 0; padding-left: 0; }+.tabs { height: 22px; flex: none; display: flex; align-items: stretch; border-bottom: 1px solid var(--Rule); padding-left: 2px; }+.tab { padding: 0 7px; display: flex; align-items: center; font-size: 10.5px; font-weight: 600; color: var(--TextTertiary); border-bottom: 2px solid transparent; margin-bottom: -1px; cursor: pointer; }+.tab:hover { color: var(--TextPrimary); }+.tab.on { color: var(--TextHeading); border-bottom-color: var(--Accent); }+.tabs .sp { flex: 1; }+.tabs .rt { display: flex; align-items: center; gap: 6px; padding-bottom: 2px; }+.content { flex: 1; display: flex; min-height: 0; }++/* sections: no fill, no frame, a Rule on the left edge facing a neighbour */+.sec { flex: none; padding: 5px 8px 4px; display: flex; flex-direction: column; gap: 4px; min-width: 0; }+.sec + .sec { border-left: 1px solid var(--Rule); }+.sec.grow { flex: 1; }+.sec-h { display: flex; align-items: center; justify-content: space-between; gap: 6px; height: 16px; }+.row { display: flex; align-items: flex-start; }+.row.c { align-items: center; }+.gap4 { gap: 4px; } .gap6 { gap: 6px; } .gap8 { gap: 8px; } .gap12 { gap: 12px; }+.fill { flex: 1; }++/* knob cell: knob → name 8/500 secondary → value mono 8 */+.kc { display: flex; flex-direction: column; align-items: center; flex: none; cursor: ns-resize; }+.kc svg { display: block; overflow: visible; }+.kc .kl { font-size: 8px; font-weight: 500; color: var(--TextSecondary); line-height: 10px; margin-top: 1px; white-space: nowrap; }+.kc .kv { font: 8px "Geist Mono", monospace; color: var(--TextPrimary); line-height: 10px; white-space: nowrap; }+.kc .groove { stroke: var(--BgSunken); }+.kc .face { fill: var(--SurfaceRaised); stroke: var(--Seam); }+.kc .ptr { stroke: var(--TextPrimary); }+.kc .arc { stroke: var(--VizInk); }+.kc .arc.mod { stroke: var(--Teal); }+.kc .oth { stroke: var(--TextFaint); }+.kc .now { fill: var(--TextMuted); }+.kc:hover .arc, .kc.drag .arc { stroke: var(--Accent); }+.kc:hover .kl, .kc.drag .kl { color: var(--TextPrimary); }++/* switch 18 × 10 */+.swl { display: inline-flex; align-items: center; gap: 4px; font-size: 8px; font-weight: 500; color: var(--TextSecondary); white-space: nowrap; cursor: pointer; }+.sw { width: 18px; height: 10px; border-radius: 2px; background: var(--BgSunken); box-shadow: 0 0 0 1px var(--Rule) inset; position: relative; flex: none; }+.sw i { position: absolute; top: 1.5px; left: 1.5px; width: 7px; height: 7px; border-radius: 1px; background: var(--TextFaint); }+.sw.on { background: var(--Accent); box-shadow: none; }+.sw.on i { left: 9.5px; background: var(--Panel); }++/* segmented group: keys butted on seams */+.seg { display: inline-flex; height: 16px; border: 1px solid var(--Seam); border-radius: 3px; overflow: hidden; flex: none; background: var(--Seam); gap: 1px; }+.seg b { display: flex; align-items: center; justify-content: center; padding: 0 5px; font-size: 9px; font-weight: 500; color: var(--TextSecondary);+ background: var(--SurfaceRaised); white-space: nowrap; cursor: pointer; }+.seg b:hover { background: var(--SurfaceHover); color: var(--TextPrimary); }+.seg b.on { background: var(--Accent); color: var(--TextOnAccent); }+.seg.fillw { display: flex; } .seg.fillw b { flex: 1; padding: 0 2px; }+.seg.lg { height: 18px; } .seg.lg b { font-size: 10px; padding: 0 7px; }++/* field / dropdown well */+.dd { height: 16px; display: inline-flex; align-items: center; justify-content: space-between; gap: 4px; padding: 0 3px 0 5px; background: var(--BgSunken);+ border: 1px solid var(--Rule); border-radius: 3px; font-size: 9px; font-weight: 500; color: var(--TextPrimary); white-space: nowrap; overflow: hidden; flex: none; }+.dd.mono { font-family: "Geist Mono", monospace; font-weight: 400; }+.dd svg { flex: none; }+.btn { height: 16px; display: inline-flex; align-items: center; gap: 4px; padding: 0 6px; background: var(--SurfaceRaised); border: 1px solid var(--Seam); border-radius: 3px;+ box-shadow: inset 0 1px 0 var(--ShadowBevel); font-size: 9px; font-weight: 500; color: var(--TextSecondary); white-space: nowrap; flex: none; cursor: default; }+.btn:hover { background: var(--SurfaceHover); color: var(--TextPrimary); }+.btn.on { background: var(--Accent); color: var(--TextOnAccent); border-color: var(--Seam); }+.lbl { font-size: 9px; font-weight: 500; color: var(--TextSecondary); white-space: nowrap; }+.mono8 { font: 8px "Geist Mono", monospace; color: var(--TextPrimary); white-space: nowrap; }+.hint { font-size: 8px; color: var(--TextTertiary); line-height: 11px; }++/* slider row: label · track · value */+.sl { display: grid; align-items: center; gap: 5px; height: 14px; cursor: ew-resize; }+.sl .ends { display: flex; justify-content: space-between; font-size: 8px; color: var(--TextTertiary); }+.sl .trk { height: 3px; border-radius: 2px; background: var(--BgSunken); box-shadow: 0 0 0 1px var(--Rule) inset; position: relative; }+.sl .trk u { position: absolute; top: 0; bottom: 0; left: 0; background: var(--VizInk); border-radius: 2px; }+.sl .trk i { position: absolute; top: -2px; width: 6px; height: 7px; margin-left: -3px; background: var(--TextPrimary); border-radius: 1px; box-shadow: 0 0 0 1px var(--Seam); }+.sl:hover .trk u { background: var(--Accent); }++/* graph window: well, rule frame, radius 3 */+.graph { background: var(--BgSunken); border: 1px solid var(--Rule); border-radius: 3px; position: relative; overflow: hidden; flex: none; }+.graph svg { position: absolute; inset: 0; display: block; }+.ax { font: 7.5px "Geist Mono", monospace; fill: var(--TextAxis); }+.gl { stroke: var(--VizGrid); stroke-width: 1; fill: none; }+.cv { stroke: var(--VizInk); stroke-width: 1.4; fill: none; stroke-linejoin: round; stroke-linecap: round; }+.cv.teal { stroke: var(--Teal); } .cv.steel { stroke: var(--Steel); } .cv.thin { stroke-width: 1; }+.nd { fill: var(--VizInk); } .nd.act { fill: var(--Accent); }++/* ADSR number cells */+.adsr { display: grid; grid-template-columns: repeat(4, 1fr); gap: 3px; }+.adsr div { display: flex; flex-direction: column; align-items: center; }+.adsr .w { width: 100%; height: 15px; display: flex; align-items: center; justify-content: center; background: var(--BgSunken); border: 1px solid var(--Rule); border-radius: 2px;+ font: 8px "Geist Mono", monospace; color: var(--TextPrimary); cursor: ns-resize; }+.adsr .w:hover { color: var(--Accent); }+.adsr span { font-size: 8px; font-weight: 500; color: var(--TextSecondary); line-height: 10px; }++/* matrix rows */+.mx-h, .mx-r { display: grid; grid-template-columns: 14px 104px 10px 138px 1fr 34px 14px; align-items: center; gap: 4px; }+.mx-h { font-size: 8px; font-weight: 500; color: var(--TextTertiary); height: 12px; }+.mx-r { height: 20px; border-top: 1px solid var(--Rule); }+.mx-r:hover { background: var(--SurfaceHover); }+.mx-r .n { font: 8px "Geist Mono", monospace; color: var(--TextFaint); text-align: right; }+.mx-r .dd { width: 100%; height: 15px; }+.bipbar { height: 7px; background: var(--BgSunken); border: 1px solid var(--Rule); border-radius: 2px; position: relative; }+.bipbar u { position: absolute; top: 1px; bottom: 1px; background: var(--Teal); border-radius: 1px; }+.bipbar i { position: absolute; top: -3px; bottom: -3px; width: 1px; background: var(--Rule); left: 50%; }+.bipbar em { position: absolute; top: -3px; width: 1px; height: 3px; background: var(--TextFaint); }+.x { display: flex; align-items: center; justify-content: center; color: var(--TextFaint); }+.x:hover { color: var(--TextPrimary); }+.scroll { flex: 1; overflow: hidden; position: relative; }+.scroll::after { content: ""; position: absolute; right: 0; top: 2px; width: 3px; height: 62%; border-radius: 2px; background: var(--Rule); }++/* inactive subtree: next ink step, never opacity */+.inactive .kl, .inactive .kv, .inactive .lbl, .inactive .swl, .inactive .seg b:not(.on), .inactive .hint { color: var(--TextDisabled) !important; }+.inactive .arc { stroke: var(--Rule) !important; }+.inactive .ptr { stroke: var(--TextDisabled); }+.inactive .sw.on, .inactive .seg b.on { background: var(--Rule); color: var(--TextSecondary); }+.inactive .cv { stroke: var(--Rule); }+.inactive .nd { fill: var(--Rule); }++/* annotations */+.ann { display: grid; grid-template-columns: 1fr 1fr; gap: 6px 36px; }+.ann ol { margin: 4px 0; padding-left: 20px; }+.ann li { margin: 3px 0; font-size: 12.5px; }+.ann li b { color: var(--TextPrimary); font-weight: 600; }+.pill { display: inline-block; font: 11px "Geist Mono", monospace; color: var(--TextMuted); border: 1px solid var(--Rule); border-radius: 3px; padding: 0 5px; margin-right: 4px; }+</style>+</head>+<body class="t-dark">+<div class="page">+ <h1>Nota Twin — device card</h1>+ <p class="lede">Design handoff for <code>TwinInstrumentCard</code> (specs/055 · US7). The card below is live: tabs, A / B, layout, S / L, knobs (drag up / down) and switches respond, so every state can be inspected. 1 px in the card = 1 logical px in Avalonia; the 2× view is only for reading.</p>++ <div class="bar">+ <span>Theme <span class="pg" id="pgTheme"><button data-v="dark" class="on">Studio Dark</button><button data-v="light">Studio Light</button></span></span>+ <span>Scale <span class="pg" id="pgZoom"><button data-v="1">1×</button><button data-v="2" class="on">2×</button></span></span>+ <span>Morph demo <span class="pg" id="pgMorph"><button data-v="0" class="on">0 %</button><button data-v="0.35">35 %</button><button data-v="1">100 %</button></span></span>+ <span>Delay <span class="pg" id="pgDly"><button data-v="1" class="on">on</button><button data-v="0">off (inactive look)</button></span></span>+ </div>++ <div class="stage">+ <div><div class="zoomwrap" id="zL"><div id="cardL"></div></div><div class="caption">L · 700 × 260</div></div>+ <div><div class="zoomwrap" id="zS"><div id="cardS"></div></div><div class="caption">S · 260 × 260 — the performance view</div></div>+ </div>++ <h2>What changes, and why</h2>+ <div class="ann" id="ann"></div>++ <h2>Frame and grid</h2>+ <table class="spec">+ <tr><th>Part</th><th>Size (logical px)</th><th>Notes</th></tr>+ <tr><td>Card</td><td>700 × 260 (S: 260 × 260)</td><td>Unchanged. Header 22 from <code>BuildCardShell</code>; body 238, inset 6.</td></tr>+ <tr><td>Status line</td><td>removed (was 18)</td><td>It repeated the header badge and the side switch. Its 18 px go to the tab body. Hints (“click a step”) move into the tab they belong to.</td></tr>+ <tr><td>Morph column</td><td>70 wide (64 + 6 gap), full body height</td><td>Rule on its right edge. Morph knob 44 (<code>KnobMain</code>), value mono 8, morph strip 56 × 3, “Edit” A | B segments (fill, 18 tall), three ghost actions 56 × 16.</td></tr>+ <tr><td>Tab row</td><td>22 tall, Rule under it</td><td>Tabs 10.5 / 600, padding 7, chosen = Ink 0 + 2 px accent underline. Right: Lower | Upper (only in Layer / Split) and Single | Layer | Split (18 tall). The “Parts” button is gone — its controls live in Voice → Part.</td></tr>+ <tr><td>Tab body</td><td>612 × 204</td><td>Sections are <code>DeviceCardKit.Section</code>, padding 5 / 8, gap 4. Titles <code>DeviceSection</code> on a 16 px header row; the header row carries the section’s switch or chooser on its right.</td></tr>+ <tr><td>Row baseline</td><td>header 16 · graph or chooser · knob row 53 (34 knob) or 62 (44 knob) · knob row · slider rows 14</td><td>Sections that sit side by side use the same row order, so knob rows line up across the tab (the old card let every island float).</td></tr>+ <tr><td>Signal chevrons</td><td>removed</td><td>The “›” between islands read as buttons and appeared where there is no signal flow (Matrix). The left-to-right order already reads as the chain.</td></tr>+ </table>++ <h2>Controls used (all existing — nothing new to build except where noted)</h2>+ <table class="spec">+ <tr><th>Control</th><th>Where</th><th>Kit</th></tr>+ <tr><td>Knob 34 / 36 / 44 + cell</td><td>everywhere</td><td><code>DeviceCardKit.KnobCell</code>, Twin’s other-side tick and “sound now” dot stay as they are.</td></tr>+ <tr><td>Segments</td><td>discrete params only: ladder slope, voice mode, LFO shape and mode, spread mode, bend range (4 steps), mod-FX type, pattern, Seq | Arp</td><td><code>DeviceCardKit.Segments</code> (16 tall in the body, 18 in the tab row).</td></tr>+ <tr><td>Slider row</td><td>continuous params that read as a position between named ends: “To filter” balance on each source, Route series ↔ parallel, multimode Mode (four marks LP · BP · HP · notch)</td><td><code>DeviceCardKit.SliderRow</code> with end words instead of a single label — <b>small addition</b>: an overload that takes end words (or N marks) under the track and an optional hidden label / value.</td></tr>+ <tr><td>ADSR cells</td><td>Env tab</td><td><code>DragNumber</code> in a 4-column grid under each graph — replaces the “1 ms · 91 ms · 50 % · 39 ms” string.</td></tr>+ <tr><td>Graphs</td><td>wave, response, envelopes, LFO, FX previews, route, step grid, pad</td><td><code>NotaGraph</code>. New read-only previews: route diagram, mod-FX sweep, delay taps, reverb tail (<code>TwinViews.cs</code>).</td></tr>+ <tr><td>Bipolar depth bar</td><td>Matrix rows</td><td><b>New</b> small view in <code>TwinViews.cs</code>: centre-zero teal bar 7 tall, other side’s depth as a faint tick; drags like a slider; double-click = 0.</td></tr>+ </table>++ <h2>States to check</h2>+ <ul>+ <li><b>Editing B</b> — the B key is the only accent in the morph column; the morph strip’s “B” end takes the accent too. Every knob shows the B value; A’s value is the faint tick outside the groove.</li>+ <li><b>Morph between</b> (35 % demo) — each knob shows a muted dot on the groove where the sound is now.</li>+ <li><b>Effect off</b> — the section’s body takes <code>Inactive</code>: inner switches that are on turn <code>Rule</code>, arcs <code>Rule</code>, labels Ink 5. Nothing orange inside an effect that is off.</li>+ <li><b>Detune</b> is inactive unless the voice mode is Unison; <b>Division</b> replaces Rate while LFO / delay Sync is on.</li>+ <li><b>Layer / Split</b> — Lower | Upper appears in the tab row; Voice’s Output section becomes Part (Volume, Pan, Octave, Split key with Learn, voice share).</li>+ <li>Both Studio themes (toggle above); Ember themes follow from tokens.</li>+ </ul>+</div>++<script>+"use strict";+const T = " ", MI = "−";+const sgn = (n, d = 0) => { const s = Math.abs(n).toFixed(d); return n > 0 && +s ? "+" + s : n < 0 && +s ? MI + s : (0).toFixed(d); };+const pctv = v => Math.round(v * 100) + T + "%";+const hz = f => f < 999.5 ? Math.round(f) + T + "Hz" : (f >= 9995 ? Math.round(f / 1000) : (f / 1000).toFixed(1)) + T + "k";+const time = s => s < 0.9995 ? (s < 0.00995 ? (s * 1000).toFixed(1) : Math.round(s * 1000)) + T + "ms" : s.toFixed(2) + T + "s";+const exp = (v, lo, hi) => lo * Math.pow(hi / lo, Math.min(1, Math.max(0, v)));+const F = {+ pct: pctv, bip: v => sgn((v - .5) * 200) + T + "%",+ cut: v => hz(20 * Math.pow(1000, v)), oct: v => sgn((v - .5) * 16, 1) + T + "oct",+ st: v => sgn(Math.round(v * 48) - 24) + T + "st", c: v => sgn(Math.round((v - .5) * 100)) + T + "c",+ atk: v => time(exp(v, .0005, 10)), dec: v => time(exp(v, .003, 15)),+ dly: v => v < .002 ? "off" : time(exp(v, .001, 5)), glide: v => v < .002 ? "off" : time(exp(v, .005, 5)),+ fade: v => v < .002 ? "off" : time(exp(v, .01, 10)),+ rate: v => { const h = exp(v, .02, 40); return h >= 9.995 ? hz(h) : h.toFixed(h < .995 ? 2 : 1) + T + "Hz"; },+ wave: v => v <= .02 ? "tri" : v < .48 ? "tri–saw" : v <= .52 ? "saw" : v < .98 ? "saw–sqr" : "square",+ width: v => pctv(.05 + .9 * v), semis: v => (v * 1).toFixed(2) + T + "st", det: v => "±" + Math.round(v * 50) + T + "c",+ voices: v => String(4 + Math.round(v * 8)), colour: v => v < .2 ? "white" : v < .6 ? "pink" : "red",+ pan: v => { const p = (v - .5) * 200; return Math.abs(p) < .5 ? "C" : (p < 0 ? "L" : "R") + Math.round(Math.abs(p)); },+ oct2: v => sgn(Math.round(v * 4) - 2) + T + "oct", key: v => noteName(Math.round(v * 127)),+ div: v => ["1/16", "1/8T", "1/8", "1/8.", "1/4T", "1/4", "1/4.", "1/2"][Math.round(v * 7)],+ sync: v => ["8 bars", "4 bars", "2 bars", "1 bar", "1/2", "1/4.", "1/4", "1/8.", "1/4T", "1/8", "1/8T", "1/16", "1/16T", "1/32"][Math.round(v * 13)],+ ms: v => time(exp(v, .01, 2)), share: v => { const l = 2 + 2 * Math.round(v * 4); return l + " + " + (12 - l); },+};+function noteName(n) { return ["C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B"][n % 12] + (Math.floor(n / 12) - 1); }++// ---- the patch: [A, B, format] -----------------------------------------------------------+const P = {+ morph: [0, 0, "pct"],+ o1wave: [.5, .82, "wave"], o1pw: [.5, .3, "width"], o1metal: [0, .35, "pct"], o1level: [1, .8, "pct"], o1coarse: [.5, .5, "st"], o1fine: [.5, .54, "c"], o1bal: [1, .6, "pct"],+ o2wave: [.5, .1, "wave"], o2pw: [.5, .5, "width"], o2metal: [0, 0, "pct"], o2level: [.45, .7, "pct"], o2coarse: [.5, .75, "st"], o2fine: [.53, .47, "c"], o2bal: [1, .3, "pct"],+ fm21: [0, .25, "pct"], fmfilt: [0, .1, "pct"],+ noiselevel: [.08, .2, "pct"], noisecolor: [.4, .7, "colour"], noisebal: [1, 1, "pct"],+ mmmode: [0, .3, "pct"], mmcut: [.82, .55, "cut"], mmres: [.1, .45, "pct"], mmkey: [0, .3, "pct"], mmenv: [.5, .68, "oct"],+ route: [1, .2, "pct"], brute: [0, .25, "pct"], drive: [.15, .4, "pct"],+ ldcut: [.62, .48, "cut"], ldres: [.1, .3, "pct"], ldkey: [.5, .5, "pct"], ldenv: [.6, .75, "oct"],+ fenva: [.05, .2, "atk"], fenvd: [.45, .6, "dec"], fenvs: [.5, .3, "pct"], fenvr: [.35, .5, "dec"], fenvvel: [.3, .5, "pct"], fenvcurve: [.5, .6, "pct"],+ aenva: [.03, .35, "atk"], aenvd: [.45, .55, "dec"], aenvs: [1, .7, "pct"], aenvr: [.3, .55, "dec"], aenvvel: [.5, .4, "pct"], aenvcurve: [.5, .5, "pct"],+ menva: [.05, .1, "atk"], menvd: [.3, .4, "dec"], menvs: [0, .2, "pct"], menvr: [.35, .4, "dec"], menvdly: [0, .3, "dly"], menvvel: [0, .2, "pct"],+ lfo1rate: [.46, .6, "rate"], lfo1div: [.6, .6, "sync"], lfo1fade: [0, .3, "fade"], lfo1amt: [1, .8, "pct"], vibamt: [.15, .3, "semis"],+ modfxrate: [.3, .4, "pct"], modfxdepth: [.5, .6, "pct"], modfxmix: [.3, .45, "pct"],+ dlydiv: [.71, .71, "div"], dlyfb: [.35, .5, "pct"], dlymix: [.25, .3, "pct"],+ rvsize: [.5, .7, "pct"], rvdamp: [.5, .4, "pct"], rvmix: [.2, .35, "pct"],+ voices: [1, 1, "voices"], glide: [0, .25, "glide"], unidetune: [.3, .3, "det"], spread: [.3, .5, "pct"], drift: [.2, .3, "pct"],+ vol: [.7, .7, "pct"], pan: [.5, .5, "pan"], octave: [.5, .5, "oct2"], splitkey: [.47, .47, "key"], share: [.5, .5, "share"],+ swing: [.5, .5, "pct"], arpgate: [.5, .5, "pct"],+ m1: [0, 0, "pct"], m2: [.25, .25, "pct"], m3: [0, 0, "pct"], m4: [.6, .6, "pct"], m5: [0, 0, "pct"], m6: [0, 0, "pct"], m7: [0, 0, "pct"], m8: [0, 0, "pct"],+};+const BIP = new Set(["o1coarse", "o1fine", "o2coarse", "o2fine", "mmenv", "ldenv", "pan", "octave"]);+const S = { tab: 0, side: 0, layout: 0, part: 0, lfo: 0, theme: "dark", morph: 0, dlyOn: 1, seqKind: 0, drag: null,+ sel: { mmmode: 0, ldslope: 1, lfoshape: 0, lfomode: 0, vmode: 0, spmode: 0, bend: 0, modfx: 0, seqpat: 0, seqpage: 0, lane: 0, arpmode: 0, arpoct: 1, seqrate: 3 },+ sw: { sync: 0, o2lo: 0, menvloop: 0, lfosync: 0, retrig: 0, modfxon: 1, dlysync: 1, pingpong: 1, rvon: 1, fxsec: 1, glidelegato: 0, seqon: 1, transpose: 1, latch: 0, smooth: 1, hold: 0 } };+const val = id => P[id][S.side];+const other = id => P[id][1 - S.side];+const now = id => P[id][0] + (P[id][1] - P[id][0]) * S.morph;+const show = id => F[P[id][2]](val(id));++// ---- primitives ---------------------------------------------------------------------------+const pt = (r, v) => { const a = (-135 + 270 * v) * Math.PI / 180; return [26 + r * Math.sin(a), 26 - r * Math.cos(a)]; };+function arcPath(r, v0, v1) {+ if (v1 < v0) [v0, v1] = [v1, v0];+ if (v1 - v0 < .002) return "";+ const [x0, y0] = pt(r, v0), [x1, y1] = pt(r, v1);+ return `M${x0.toFixed(2)} ${y0.toFixed(2)}A${r} ${r} 0 ${(v1 - v0) * 270 > 180 ? 1 : 0} 1 ${x1.toFixed(2)} ${y1.toFixed(2)}`;+}+function knobSvg(id, size, mod, plain) {+ const v = plain ? plain : val(id), bip = BIP.has(id);+ const [px, py] = pt(9, v), [ox0, oy0] = pt(24.2, plain ? v : other(id)), [ox1, oy1] = pt(26.8, plain ? v : other(id));+ const showOther = !plain && Math.abs(other(id) - v) > .004, n = plain ? v : now(id), showNow = !plain && S.morph > 0 && S.morph < 1 && Math.abs(n - v) > .004;+ const [nx, ny] = pt(21, n);+ return `<svg width="${size}" height="${size}" viewBox="0 0 52 52">+ <path class="groove" d="${arcPath(21, 0, 1)}" fill="none" stroke-width="5" stroke-linecap="butt"/>+ <path class="arc${mod ? " mod" : ""}" d="${arcPath(21, bip ? .5 : 0, v)}" fill="none" stroke-width="5" stroke-linecap="butt"/>+ ${showOther ? `<line class="oth" x1="${ox0}" y1="${oy0}" x2="${ox1}" y2="${oy1}" stroke-width="1.6"/>` : ""}+ ${showNow ? `<circle class="now" cx="${nx}" cy="${ny}" r="2"/>` : ""}+ <circle class="face" cx="26" cy="26" r="14" stroke-width="1"/>+ <line class="ptr" x1="26" y1="26" x2="${px}" y2="${py}" stroke-width="2.4" stroke-linecap="round"/></svg>`;+}+function K(id, label, o = {}) {+ const size = o.size || 34, cell = o.cell || (size === 44 ? 58 : 46);+ return `<div class="kc${S.drag === id ? " drag" : ""}${o.cls ? " " + o.cls : ""}" data-k="${id}" style="width:${cell}px">${knobSvg(id, size, o.mod)}+ <div class="kl">${label}</div><div class="kv">${o.text || show(id)}</div></div>`;+}+const SW = (id, label) => `<span class="swl" data-sw="${id}"><span class="sw${S.sw[id] ? " on" : ""}"><i></i></span>${label}</span>`;+const SEG = (id, items, cls = "") => `<span class="seg ${cls}">${items.map((t, i) => `<b class="${S.sel[id] === i ? "on" : ""}" data-seg="${id}" data-i="${i}">${t}</b>`).join("")}</span>`;+const SEGX = (items, on, act, cls = "") => `<span class="seg ${cls}">${items.map((t, i) => `<b class="${on === i ? "on" : ""}" data-act="${act}" data-i="${i}">${t}</b>`).join("")}</span>`;+const chev = `<svg width="8" height="8" viewBox="0 0 16 16"><path d="M4 6l4 4 4-4" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>`;+const DD = (text, w, mono) => `<span class="dd${mono ? " mono" : ""}" style="${w ? `width:${w}px` : ""}"><span>${text}</span><span style="color:var(--TextMuted);display:flex">${chev}</span></span>`;+const SEC = (title, right, body, o = {}) => `<div class="sec${o.grow ? " grow" : ""}${o.cls ? " " + o.cls : ""}" style="${o.w ? `width:${o.w}px` : ""}">+ <div class="sec-h"><span class="sect-t">${title}</span>${right ? `<span class="row c gap8">${right}</span>` : ""}</div>${body}</div>`;+const ROW = (...xs) => `<div class="row">${xs.join("")}</div>`;+function SL(id, left, right, o = {}) {+ const v = val(id);+ return `<div class="sl" data-sl="${id}" style="grid-template-columns:${o.bare ? "1fr" : `${o.lw || 38}px 1fr 32px`}">+ ${o.bare ? "" : `<span class="lbl">${o.label || ""}</span>`}+ <div><div class="trk"><u style="width:${v * 100}%"></u><i style="left:${v * 100}%"></i></div><div class="ends" style="margin-top:2px">${(o.marks || [left, right]).map(x => `<span>${x}</span>`).join("")}</div></div>+ ${o.bare ? "" : `<span class="mono8" style="text-align:right">${o.text ? o.text(v) : pctv(v)}</span>`}</div>`;+}+function G(w, h, inner) { return `<div class="graph" style="width:${w}px;height:${h}px"><svg width="${w - 2}" height="${h - 2}">${inner(w - 2, h - 2)}</svg></div>`; }+const poly = (pts, cls = "cv") => `<polyline class="${cls}" points="${pts.map(p => p[0].toFixed(1) + "," + p[1].toFixed(1)).join(" ")}"/>`;++// ---- graphs --------------------------------------------------------------------------------+function oscSample(ph, wave, pw) {+ const tri = ph < .5 ? 4 * ph - 1 : 3 - 4 * ph, saw = 2 * ph - 1, sq = ph < pw ? 1 : -1;+ return wave <= .5 ? tri + (saw - tri) * (wave / .5) : saw + (sq - saw) * ((wave - .5) / .5);+}+const waveG = (n, w) => G(w, 34, (W, H) => {+ const wave = val(`o${n}wave`), pw = .05 + .9 * val(`o${n}pw`), metal = val(`o${n}metal`), pts = [];+ for (let i = 0; i <= 160; i++) { const ph = (i / 80) % 1; let s = oscSample(ph, wave, pw); s = s * (1 - metal) + Math.sin(s * Math.PI * 2.5) * metal; pts.push([4 + i / 160 * (W - 8), H / 2 - s * (H / 2 - 5)]); }+ return `<line class="gl" x1="0" y1="${H / 2}" x2="${W}" y2="${H / 2}"/>` + poly(pts);+});+const noiseG = w => G(w, 34, (W, H) => {+ const c = val("noisecolor"), pts = [];+ for (let i = 0; i <= 40; i++) { const x = i / 40, y = .25 + x * c * .6; pts.push([4 + x * (W - 8), 5 + y * (H - 10)]); }+ return poly(pts) + `<text class="ax" x="4" y="${H - 3}">20</text><text class="ax" x="${W - 3}" y="${H - 3}" text-anchor="end">20k</text><text class="ax" x="${W - 3}" y="9" text-anchor="end">${F.colour(c)}</text>`;+});+function lp(f, fc, q, poles) { const r = f / fc; return -10 * poles / 2 * Math.log10(1 + Math.pow(r, 4)) / 2 * 1 + (q * 14) * Math.exp(-Math.pow(Math.log2(r) * 3, 2)); }+const responseG = (w, h) => G(w, h, (W, H) => {+ const fm = 20 * Math.pow(1000, val("mmcut")), fl = 20 * Math.pow(1000, val("ldcut")), poles = S.sel.ldslope ? 4 : 2, mode = Math.round(val("mmmode") * 3);+ const y = db => 10 + (-db / 48) * (H - 22) + 8;+ const mm = [], ld = [], cb = [];+ for (let i = 0; i <= 120; i++) {+ const f = 20 * Math.pow(1000, i / 120), x = i / 120 * W;+ let a = lp(f, fm, val("mmres"), 2);+ if (mode === 2) a = lp(fm * fm / f, fm, val("mmres"), 2);+ if (mode === 1) a = Math.min(lp(f, fm, val("mmres"), 2), lp(fm * fm / f, fm, val("mmres"), 2)) + 3;+ if (mode === 3) a = -18 * Math.exp(-Math.pow(Math.log2(f / fm) * 4, 2));+ const b = lp(f, fl, val("ldres"), poles), r = val("route");+ const c = r * (10 * Math.log10((Math.pow(10, a / 10) + Math.pow(10, b / 10)) / 2) ) + (1 - r) * (a + b);+ mm.push([x, Math.min(H - 2, y(a))]); ld.push([x, Math.min(H - 2, y(b))]); cb.push([x, Math.min(H - 2, y(c))]);+ }+ const gx = [100, 1000, 10000].map(f => Math.log10(f / 20) / 3 * W);+ return gx.map(x => `<line class="gl" x1="${x}" y1="0" x2="${x}" y2="${H}"/>`).join("") + `<line class="gl" x1="0" y1="${y(0)}" x2="${W}" y2="${y(0)}"/>`+ + poly(mm, "cv teal thin") + poly(ld, "cv steel thin") + poly(cb)+ + `<circle class="nd act" cx="${Math.log10(fl / 20) / 3 * W}" cy="${y(0) - 1}" r="3"/>`+ + `<text class="ax" x="3" y="${H - 3}">20</text><text class="ax" x="${W - 3}" y="${H - 3}" text-anchor="end">20k</text>`+ + `<text class="ax" x="${W - 3}" y="9" text-anchor="end" style="fill:var(--Teal)">multi</text><text class="ax" x="${W - 3}" y="18" text-anchor="end" style="fill:var(--Steel)">ladder</text>`;+});+const routeG = (w, h) => G(w, h, (W, H) => {+ const r = val("route"), par = r >= .5, box = (x, y, t) => `<rect x="${x}" y="${y}" width="26" height="13" rx="2" fill="none" stroke="var(--VizInk)" stroke-width="1"/><text class="ax" x="${x + 13}" y="${y + 9.5}" text-anchor="middle" style="fill:var(--TextSecondary)">${t}</text>`;+ const mid = H / 2 + 4, lab = `<text class="ax" x="3" y="9">${r <= .01 ? "series" : r >= .99 ? "parallel" : Math.round(r * 100) + T + "% parallel"}</text>`;+ return lab + (par+ ? `<path class="cv thin" d="M4 ${mid}H18V${mid - 10}H${W / 2 - 13}M18 ${mid}V${mid + 10}H${W / 2 - 13}M${W / 2 + 13} ${mid - 10}H${W - 18}V${mid + 10}H${W / 2 + 13}M${W - 18} ${mid}H${W - 4}"/>` + box(W / 2 - 13, mid - 16.5, "multi") + box(W / 2 - 13, mid + 3.5, "ladder")+ : `<path class="cv thin" d="M4 ${mid}H${W / 2 - 34}M${W / 2 - 8} ${mid}H${W / 2 + 8}M${W / 2 + 34} ${mid}H${W - 4}"/>` + box(W / 2 - 34, mid - 6.5, "multi") + box(W / 2 + 8, mid - 6.5, "ladder"));+});+function envG(e, w, h, mod) {+ return G(w, h, (W, H) => {+ const a = val(e + "a"), d = val(e + "d"), s = val(e + "s"), r = val(e + "r"), dl = mod ? val("menvdly") : 0;+ const tot = 4, xs = v => 4 + v * (W - 8) / tot, yb = H - 5, yt = 6, sy = yb - s * (yb - yt);+ const x0 = xs(dl * .6), x1 = x0 + Math.max(2, a * (W - 8) / tot), x2 = x1 + Math.max(3, d * (W - 8) / tot), x3 = xs(3), x4 = Math.min(W - 4, x3 + Math.max(3, r * (W - 8) / tot));+ const seg = (xa, ya, xb, yb2, k) => { const p = []; for (let i = 0; i <= 16; i++) { const t = i / 16, q = k > 0 ? 1 - Math.pow(1 - t, 3) : t; p.push([xa + (xb - xa) * t, ya + (yb2 - ya) * q]); } return p; };+ const pts = [[4, yb], [x0, yb], ...seg(x0, yb, x1, yt, 0), ...seg(x1, yt, x2, sy, 1), [x3, sy], ...seg(x3, sy, x4, yb, 1)];+ return `<line class="gl" x1="${x3}" y1="0" x2="${x3}" y2="${H}" stroke-dasharray="2 2"/>` + poly(pts)+ + [[x1, yt], [x2, sy], [x4, yb]].map(([x, y], i) => `<circle class="nd${i === 1 && e === "aenv" ? " act" : ""}" cx="${x}" cy="${y}" r="2.6"/>`).join("");+ });+}+function lfoShape(ph, k) {+ switch (k) {+ case 0: return Math.sin(ph * 2 * Math.PI);+ case 1: return ph < .25 ? ph * 4 : ph < .75 ? 2 - ph * 4 : ph * 4 - 4;+ case 2: return 1 - 2 * ph;+ case 3: return ph < .5 ? 1 : -1;+ case 4: return [.6, -.3, .9, -.8, .1, -.5, .4, -.9][Math.floor(ph * 8)];+ default: { const v = [.6, -.3, .9, -.8, .1, -.5, .4, -.9, .6], i = ph * 8, f = i - Math.floor(i); const a = v[Math.floor(i)], b = v[Math.floor(i) + 1]; return a + (b - a) * (1 - Math.cos(f * Math.PI)) / 2; }+ }+}+const lfoG = (w, h) => G(w, h, (W, H) => {+ const pts = [], k = S.sel.lfoshape;+ for (let i = 0; i <= 200; i++) { const ph = i / 200 * 2 % 1; pts.push([4 + i / 200 * (W - 8), H / 2 - lfoShape(ph, k) * (H / 2 - 8)]); }+ const px = 4 + .37 * (W - 8);+ return `<line class="gl" x1="0" y1="${H / 2}" x2="${W}" y2="${H / 2}"/><line class="gl" x1="${W / 2}" y1="0" x2="${W / 2}" y2="${H}"/>` + poly(pts)+ + `<line x1="${px}" y1="0" x2="${px}" y2="${H}" stroke="var(--Accent)" stroke-width="1"/>`+ + `<text class="ax" x="3" y="${H - 3}">0</text><text class="ax" x="${W - 3}" y="${H - 3}" text-anchor="end">2 cycles</text>`;+});+const modfxG = w => G(w, 40, (W, H) => {+ const pts = [], rate = 1 + val("modfxrate") * 4, depth = val("modfxdepth");+ for (let i = 0; i <= 120; i++) { const x = i / 120; pts.push([4 + x * (W - 8), H / 2 - Math.sin(x * rate * 2 * Math.PI) * depth * (H / 2 - 5)]); }+ return `<line class="gl" x1="0" y1="${H / 2}" x2="${W}" y2="${H / 2}"/>` + poly(pts) + `<text class="ax" x="${W - 3}" y="9" text-anchor="end">sweep</text>`;+});+const delayG = w => G(w, 40, (W, H) => {+ let s = `<line class="gl" x1="0" y1="${H / 2}" x2="${W}" y2="${H / 2}"/>`, a = 1, x = 6;+ const step = 10 + val("dlydiv") * 14, fb = val("dlyfb");+ s += `<rect x="${x - 1}" y="${H / 2 - (H / 2 - 4)}" width="2" height="${H / 2 - 4}" rx="1" fill="var(--TextFaint)"/>`;+ for (let i = 1; x + step < W - 4 && a > .04; i++) {+ x += step; a = i === 1 ? .8 : a * fb * 1.6;+ const hgt = Math.min(1, a) * (H / 2 - 4), up = !S.sw.pingpong || i % 2;+ s += `<rect x="${x - 1}" y="${up ? H / 2 - hgt : H / 2}" width="2" height="${hgt}" rx="1" fill="var(--VizInk)" class="nd"/>`;+ }+ return s + `<text class="ax" x="${W - 3}" y="9" text-anchor="end">L</text><text class="ax" x="${W - 3}" y="${H - 3}" text-anchor="end">R</text>`;+});+const reverbG = w => G(w, 40, (W, H) => {+ const pts = [], sz = .5 + val("rvsize") * 3, dm = val("rvdamp");+ for (let i = 0; i <= 60; i++) { const x = i / 60; pts.push([4 + x * (W - 8), 5 + (1 - Math.exp(-x * 5 / sz)) * (H - 10) * (0.7 + dm * .3)]); }+ return poly(pts) + `<text class="ax" x="${W - 3}" y="9" text-anchor="end">tail</text>`;+});+const padG = (sz, legend, w) => G(w || sz + 10, sz, (W, H) => {+ const x = .62 * W, y = .38 * H;+ return `<line class="gl" x1="${W / 2}" y1="0" x2="${W / 2}" y2="${H}"/><line class="gl" x1="0" y1="${H / 2}" x2="${W}" y2="${H / 2}"/>`+ + `<circle cx="${x}" cy="${y}" r="9" fill="none" stroke="var(--VizGrid)" stroke-width="1"/><circle cx="${x}" cy="${y}" r="4.5" fill="var(--VizInk)"/>`+ + (legend ? `<text class="ax" x="${W - 3}" y="${H / 2 - 3}" text-anchor="end">X</text><text class="ax" x="${W / 2 + 3}" y="9">Y</text>` : "");+});++// ---- tabs ------------------------------------------------------------------------------------+const TABS = ["Osc", "Filter", "Env", "LFO", "Matrix", "FX", "Seq", "Voice"];+const toFilter = (id) => SL(id, "multi", "ladder", { label: "To filter", text: v => v <= .005 ? "multi" : v >= .995 ? "ladder" : pctv(v) });+function tabOsc() {+ const osc = n => {+ const o = "o" + n;+ return ROW(K(o + "wave", "Wave"), K(o + "pw", "Width"), K(o + "metal", "Metal"), K(o + "level", "Level"))+ + ROW(K(o + "coarse", "Coarse"), K(o + "fine", "Fine"), ...(n === 2 ? [K("fm21", "FM 1", { mod: true }), K("fmfilt", "FM cut", { mod: true })] : []));+ };+ return SEC("Osc 1", "", waveG(1, 196) + osc(1) + toFilter("o1bal"), { w: 212 })+ + SEC("Osc 2", SW("sync", "Sync") + SW("o2lo", "Low"), waveG(2, 196) + osc(2) + toFilter("o2bal"), { w: 212 })+ + SEC("Noise", "", noiseG(170) + ROW(K("noiselevel", "Level"), K("noisecolor", "Colour")) + `<div style="height:53px"></div>` + toFilter("noisebal"), { grow: true });+}+function tabFilter() {+ return SEC("Multimode", "", SL("mmmode", "", "", { bare: true, marks: ["LP", "BP", "HP", "notch"] })+ + ROW(K("mmcut", "Cutoff", { size: 44, cell: 64 }), K("mmres", "Resonance", { size: 44, cell: 64 }))+ + ROW(K("mmkey", "Key", { mod: true, cell: 64 }), K("mmenv", "Env", { mod: true, cell: 64 })), { w: 144 })+ + SEC("Route", "", SL("route", "series", "parallel", { bare: true })+ + routeG(116, 62) + ROW(K("brute", "Brute", { cell: 58 }), K("drive", "Drive", { cell: 58 })), { w: 132 })+ + SEC("Ladder", SEG("ldslope", ["12", "24"]), `<div style="height:16px" class="row c"><span class="hint">dB per octave</span></div>`+ + ROW(K("ldcut", "Cutoff", { size: 44, cell: 64 }), K("ldres", "Resonance", { size: 44, cell: 64 }))+ + ROW(K("ldkey", "Key", { mod: true, cell: 64 }), K("ldenv", "Env", { mod: true, cell: 64 })), { w: 144 })+ + SEC("Response", "", responseG(176, 172), { grow: true });+}+function tabEnv() {+ const env = (t, e, mod) => {+ const cells = [["A", e + "a"], ["D", e + "d"], ["S", e + "s"], ["R", e + "r"]];+ return SEC(t, mod ? SW("menvloop", "Loop") : "", envG(e, 186, 70, mod)+ + `<div class="adsr">${cells.map(([l, id]) => `<div><div class="w">${show(id)}</div><span>${{ A: "Attack", D: "Decay", S: "Sustain", R: "Release" }[l]}</span></div>`).join("")}</div>`+ + `<div class="row" style="justify-content:center;margin-top:2px">${mod ? K("menvdly", "Delay", { cell: 58 }) + K("menvvel", "Velocity", { mod: true, cell: 58 }) : K(e + "vel", "Velocity", { mod: true, cell: 58 }) + K(e + "curve", "Curve", { cell: 58 })}</div>`, { w: 204, grow: mod });+ };+ return env("Filter env", "fenv", false) + env("Amp env", "aenv", false) + env("Mod env", "menv", true);+}+function tabLfo() {+ const synced = S.sw.lfosync;+ return SEC("LFO", SEGX(["LFO 1", "LFO 2", "LFO 3"], S.lfo, "lfo"),+ `<div class="row gap12"><div style="width:206px;display:flex;flex-direction:column;gap:6px">`+ + SEG("lfoshape", ["Sine", "Tri", "Saw", "Square", "S&H", "Smooth"], "fillw")+ + `<div class="row c gap8">${SW("lfosync", "Sync")}${SW("retrig", "Retrig")}<span class="fill"></span>${SEG("lfomode", ["Voice", "Global"])}</div>`+ + ROW(synced ? K("lfo1div", "Division", { size: 44, cell: 64 }) : K("lfo1rate", "Rate", { size: 44, cell: 64 }), K("lfo1fade", "Fade", { size: 44, cell: 64 }), K("lfo1amt", "Amount", { size: 44, cell: 64, mod: true }))+ + `<div class="hint">${S.lfo === 2 ? "LFO 3 adds Symmetry and Curve to this row." : "Double-click the graph to reset the phase offset."}</div>`+ + `</div>${lfoG(258, 166)}</div>`, { w: 500 })+ + SEC("Vibrato", "", `<div class="row" style="justify-content:center;margin-top:8px">${K("vibamt", "Depth", { size: 44, mod: true, cell: 80 })}</div><div class="hint" style="text-align:center">LFO 1 × mod wheel</div>`, { grow: true });+}+function tabMatrix() {+ const R = [["Pressure", "Ladder cutoff", .15, .3], ["Pressure", "Multimode cutoff", .15, .1], ["Slide", "Multimode cutoff", .2, .2], ["Pad X", "Multimode cutoff", .2, .35],+ ["Pad Y", "Morph", .5, .5], ["Mod env", "Osc 2 coarse", -.25, .4], ["LFO 2", "Pan", .1, -.2]];+ const x = `<svg width="8" height="8" viewBox="0 0 16 16"><path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>`;+ const arr = `<svg width="10" height="8" viewBox="0 0 16 16" style="color:var(--TextFaint)"><path d="M2 8h11M9 4l4 4-4 4" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>`;+ const rows = R.map(([s, d, a, b], i) => {+ const v = S.side ? b : a, o = S.side ? a : b, l = v < 0 ? 50 + v * 50 : 50, w = Math.abs(v) * 50;+ return `<div class="mx-r"><span class="n">${i + 1}</span>${DD(s)}${arr}${DD(d)}<div class="bipbar"><i></i><u style="left:${l}%;width:${w}%"></u><em style="left:${50 + o * 50}%"></em></div><span class="mono8" style="text-align:right">${sgn(v * 100)}${T}%</span><span class="x">${x}</span></div>`;+ }).join("");+ return SEC("Routes", `<span class="badge">7 / 64</span><span class="btn">+ Route</span>`,+ `<div class="mx-h"><span></span><span>Source</span><span></span><span>Destination</span><span>Depth ${S.side ? "B" : "A"}</span><span></span><span></span></div><div class="scroll">${rows}</div>`, { w: 412 })+ + SEC("Macros", "", `<div class="row" style="flex-wrap:wrap;row-gap:4px">${[1, 2, 3, 4, 5, 6, 7, 8].map(i => K("m" + i, "Macro " + i)).join("")}</div><div class="hint">Macros are matrix sources; rename with a double-click on the name.</div>`, { grow: true });+}+function tabFx() {+ const dOff = !S.dlyOn;+ return SEC("Mod FX", SW("modfxon", "On"), SEG("modfx", ["Chorus", "Flanger", "Phaser", "Ensemble"], "fillw") + modfxG(162) + ROW(K("modfxrate", "Rate", { size: 44, cell: 54 }), K("modfxdepth", "Depth", { size: 44, cell: 54 }), K("modfxmix", "Mix", { size: 44, cell: 54 })), { w: 178 })+ + SEC("Delay", `<span class="swl" data-act="dly"><span class="sw${S.dlyOn ? " on" : ""}"><i></i></span>On</span>`,+ `<div class="row c gap8" style="height:16px">${SW("dlysync", "Sync")}${SW("pingpong", "Ping-pong")}</div>` + delayG(162)+ + ROW(S.sw.dlysync ? K("dlydiv", "Division", { size: 44, cell: 54 }) : K("dlydiv", "Time", { size: 44, cell: 54, text: "350" + T + "ms" }), K("dlyfb", "Feedback", { size: 44, cell: 54 }), K("dlymix", "Mix", { size: 44, cell: 54 })), { w: 178, cls: dOff ? "inactive" : "" })+ + SEC("Reverb", SW("rvon", "On"), `<div style="height:16px"></div>` + reverbG(162) + ROW(K("rvsize", "Size", { size: 44, cell: 54 }), K("rvdamp", "Damping", { size: 44, cell: 54 }), K("rvmix", "Mix", { size: 44, cell: 54 })), { w: 178 })+ + SEC("All", "", `<div style="margin-top:2px">${SW("fxsec", "On")}</div><div class="hint" style="margin-top:4px">Off bypasses all three, to use Nota’s effect devices instead.</div>`, { grow: true });+}+function seqGrid(W, H) {+ const steps = [[60, 64, 67], [], [62], [], [60, 63, 67], [], [], [65], [64, 67, 71], [], [62], [60], [57, 60, 64], [], [55], []];+ const lo = 52, hi = 74, cw = (W - 2) / 16, play = 4, sel = 8, vel = [.9, 0, .6, 0, .8, 0, 0, .5, 1, 0, .6, .7, .9, 0, .5, 0];+ let s = "";+ for (let i = 0; i < 16; i++) {+ const x = 1 + i * cw;+ if (i % 4 === 0 && i) s += `<line class="gl" x1="${x}" y1="0" x2="${x}" y2="${H}" style="stroke:var(--Rule)"/>`;+ else if (i) s += `<line class="gl" x1="${x}" y1="0" x2="${x}" y2="${H}"/>`;+ if (i === play) s += `<rect x="${x}" y="0" width="${cw}" height="${H}" fill="var(--AccentSubtle)"/>`;+ for (const n of steps[i]) { const y = 4 + (hi - n) / (hi - lo) * (H - 22); s += `<rect x="${x + 2}" y="${y}" width="${cw - 4}" height="4" rx="1" fill="var(--VizInk)"/>`; }+ if (vel[i]) s += `<rect x="${x + 3}" y="${H - 2 - vel[i] * 11}" width="${cw - 6}" height="${vel[i] * 11}" rx="1" fill="var(--TextFaint)"/>`;+ if (i === sel) s += `<rect x="${x + .5}" y=".5" width="${cw - 1}" height="${H - 1}" rx="2" fill="none" stroke="var(--Accent)" stroke-width="1"/>`;+ }+ return s + `<line class="gl" x1="0" y1="${H - 15}" x2="${W}" y2="${H - 15}"/>`;+}+function laneGrid(W, H) {+ const v = [.2, .25, .35, .5, .65, .7, .7, .6, .5, .45, .4, .4, .5, .6, .55, .3], cw = (W - 2) / 16;+ return v.map((a, i) => `<rect x="${1 + i * cw + 3}" y="${H - 2 - a * (H - 4)}" width="${cw - 6}" height="${a * (H - 4)}" rx="1" fill="var(--Teal)"/>`).join("");+}+function tabSeq() {+ const head = `<div class="row c gap8">${SW("seqon", "Sequencer")}${SEGX(["Seq", "Arp"], S.seqKind, "seqkind")}`+ + (S.layout ? `<span class="lbl">Plays</span>${SEGX(["Lower", "Upper", "Both"], 2, "noop")}` : "") + `<span class="fill"></span>`;+ if (S.seqKind === 1) {+ return SEC("Arpeggiator", `${SW("seqon", "On")}${SEGX(["Seq", "Arp"], 1, "seqkind")}`,+ `<div class="row c gap8"><span class="lbl">Mode</span>${SEG("arpmode", ["Up", "Down", "Up/down", "Random", "As played", "Chord"])}<span class="lbl">Rate</span>${DD("1/16", 44, true)}<span class="lbl">Octaves</span>${SEG("arpoct", ["1", "2", "3", "4"])}${SW("hold", "Hold")}</div>`+ + `<div class="row gap12" style="margin-top:4px">${G(420, 120, (W, H) => { let s = ""; const n = [0, 4, 7, 12, 16, 19, 24, 28], cw = W / 16; for (let i = 0; i < 16; i++) { const k = n[i % 8]; s += `<rect x="${i * cw + 2}" y="${H - 8 - k * 3.4}" width="${cw * .5 * (.4 + val("arpgate"))}" height="4" rx="1" fill="${i === 5 ? "var(--Accent)" : "var(--VizInk)"}"/>`; } return s + `<text class="ax" x="${W - 3}" y="9" text-anchor="end">2 octaves · up</text>`; })}`+ + `<div>${ROW(K("arpgate", "Gate", { size: 44, cell: 64 }), K("swing", "Swing", { size: 44, cell: 64 }))}<div class="hint" style="width:128px;margin-top:6px">Hold a chord to hear it. Hold keeps it after release.</div></div></div>`, { grow: true });+ }+ return SEC("Sequencer", `${S.layout ? `<span class="lbl">Plays</span>${SEGX(["Lower", "Upper", "Both"], 2, "noop")}` : ""}<span class="btn"><svg width="7" height="7" viewBox="0 0 16 16"><circle cx="8" cy="8" r="6" fill="var(--Record)"/></svg>Record</span><span class="btn">To clip</span>${SW("seqon", "On")}${SEGX(["Seq", "Arp"], 0, "seqkind")}`,+ `<div class="row c gap6"><span class="lbl">Pattern</span>${SEG("seqpat", ["1", "2", "3", "4", "5", "6", "7", "8"])}<span class="lbl" style="margin-left:4px">Length</span>${DD("16", 34, true)}<span class="lbl">Rate</span>${DD("1/16", 44, true)}`+ + `<span class="lbl">Swing</span><span class="mono8">50${T}%</span>${SW("transpose", "Transpose")}${SW("latch", "Latch")}</div>`+ + G(594, 78, seqGrid)+ + `<div class="row c gap6"><span class="lbl" style="width:42px">Motion</span>${SEG("lane", ["1", "2", "3", "4"])}${DD("Morph", 96)}${SW("smooth", "Smooth")}<span class="btn">Arm</span><span class="btn">Clear</span><span class="fill"></span><span class="lbl">Steps</span>${SEG("seqpage", ["1–16", "17–32", "33–48", "49–64"])}</div>`+ + G(594, 26, laneGrid)+ + `<div class="row c gap8"><span class="mono8" style="color:var(--TextSecondary)">Step 9 · E4 G4 B4 · velocity 127 · gate 50${T}%</span><span class="btn">Rest</span><span class="btn">Tie</span><span class="fill"></span><span class="hint">Click a step to edit it; hold keys while Record is on to enter chords.</span></div>`, { grow: true });+}+function tabVoice() {+ const unison = S.sel.vmode === 3;+ const part = S.layout+ ? SEC(S.part ? "Upper part" : "Lower part", "", ROW(K("vol", "Volume"), K("pan", "Pan"), K("octave", "Octave"))+ + `<div class="row c gap6" style="margin-top:2px">${S.layout === 2 ? `<span class="lbl">Split</span>${DD(show("splitkey"), 40, true)}<span class="btn">Learn</span>` : `<span class="hint">Layer: both parts play every key.</span>`}</div>`+ + `<div class="row c gap6"><span class="lbl">Voices</span>${DD(show("share"), 52, true)}</div>`+ + `<div class="row c gap6"><span class="lbl">Bend</span>${SEG("bend", ["±2", "±5", "±12", "±24"])}</div>`, { w: 160 })+ : SEC("Output", "", ROW(K("vol", "Volume", { size: 44, cell: 58 }), K("pan", "Pan", { size: 44, cell: 58 }))+ + `<div style="display:flex;flex-direction:column;gap:3px;margin-top:4px"><span class="cap">Bend range</span>${SEG("bend", ["±2", "±5", "±12", "±24"], "fillw")}</div>`, { w: 140 });+ return SEC("Voices", SEG("vmode", ["Poly", "Mono", "Legato", "Unison"]),+ ROW(K("voices", "Voices", { size: 44, cell: 58 }), K("glide", "Glide", { size: 44, cell: 58 }), K("unidetune", "Detune", { size: 44, cell: 58, cls: unison ? "" : "inactive" }))+ + `<div style="margin-top:2px">${SW("glidelegato", "Glide only legato")}</div>`+ + `<div class="hint">${unison ? "Unison stacks every voice on one note." : "Detune works in Unison."}</div>`, { w: 200 })+ + SEC("Stereo", "", ROW(K("spread", "Spread", { size: 44, cell: 58 }), K("drift", "Drift", { size: 44, cell: 58 }))+ + `<div style="display:flex;flex-direction:column;gap:3px;margin-top:4px"><span class="cap">Spread by</span>${SEG("spmode", ["Voice", "Key", "Unison"], "fillw")}</div>`, { w: S.layout ? 118 : 132 })+ + part+ + SEC("Pad", "", padG(S.layout ? 108 : 112, true) + `<div class="mono8" style="color:var(--TextSecondary)">X 62${T}% · Y 62${T}% · Z 0${T}%</div><div class="hint">X cutoff · Y morph · Z vibrato</div>`, { grow: true });+}+const TABF = [tabOsc, tabFilter, tabEnv, tabLfo, tabMatrix, tabFx, tabSeq, tabVoice];++// ---- the card --------------------------------------------------------------------------------+function header(mini) {+ return `<div class="hdr"${mini ? ` style="grid-template-columns:1fr auto"` : ""}><span class="nm">${mini ? "Twin" : "Nota Twin"}</span>`+ + (mini ? "" : `<span class="preset"><span>${chevL}</span><span class="pn">Twin EP${S.dirty ? " *" : ""}${chev}</span><span>${chevR}</span></span>`)+ + `<span class="rt"><span class="badge">${mini ? "" : "Morphing poly · "}3/12</span>${SEGX(["S", "L"], mini ? 0 : 1, "noop")}<span class="sw on" style="margin-left:2px"><i></i></span></span></div>`;+}+const chevL = `<svg width="8" height="8" viewBox="0 0 16 16"><path d="M10 4l-4 4 4 4" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>`;+const chevR = `<svg width="8" height="8" viewBox="0 0 16 16"><path d="M6 4l4 4-4 4" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>`;+function morphCol(mini) {+ const m = S.morph;+ return `<div class="morph"${mini ? ` style="width:64px"` : ""}><span class="sect-t">Morph</span>+ <div style="margin-top:4px">${`<div class="kc" data-k="morph" style="width:58px">${knobSvg("morph", 44, false, m || .0001)}<div class="kv" style="font-size:9px;margin-top:1px">${Math.round(m * 100)}${T}%</div></div>`}</div>+ <div class="mstrip"><b class="${S.side === 0 ? "on" : ""}">A</b><div class="tr"><i style="left:${m * 100}%"></i></div><b class="${S.side === 1 ? "on" : ""}">B</b></div>+ <div style="margin-top:12px;width:56px"><div class="cap" style="text-align:center;margin-bottom:3px">Edit</div>${SEGX(["A", "B"], S.side, "side", "fillw lg")}</div>+ ${mini ? "" : `<div style="margin-top:10px;display:flex;flex-direction:column;gap:2px"><span class="ghost">A → B</span><span class="ghost">B → A</span><span class="ghost">Swap</span></div>`}+ </div>`;+}+function renderL() {+ const tabs = TABS.map((t, i) => `<span class="tab${S.tab === i ? " on" : ""}" data-tab="${i}">${t}</span>`).join("");+ const right = (S.layout ? SEGX(["Lower", "Upper"], S.part, "part", "lg") : "") + SEGX(["Single", "Layer", "Split"], S.layout, "layout", "lg");+ return `<div class="card">${header(false)}<div class="body">${morphCol(false)}+ <div class="main"><div class="tabs">${tabs}<span class="sp"></span><span class="rt">${right}</span></div>+ <div class="content">${TABF[S.tab]()}</div></div></div></div>`;+}+function renderS() {+ return `<div class="card mini">${header(true)}<div class="body">${morphCol(true)}+ <div class="main" style="padding-left:8px;gap:6px;justify-content:space-between">+ ${padG(124, false, 172)}+ <div class="row" style="justify-content:space-between;padding-right:4px">${K("ldcut", "Cutoff", { cell: 40 })}${K("ldres", "Reso", { cell: 40 })}${K("aenva", "Attack", { cell: 40 })}${K("aenvr", "Release", { cell: 40 })}</div>+ </div></div></div>`;+}+function render() {+ document.getElementById("cardL").innerHTML = renderL();+ document.getElementById("cardS").innerHTML = renderS();+ document.body.className = "t-" + S.theme;+}++// ---- interaction -----------------------------------------------------------------------------+document.addEventListener("click", e => {+ const t = e.target.closest("[data-tab],[data-seg],[data-sw],[data-act]");+ if (!t) return;+ if (t.dataset.tab) S.tab = +t.dataset.tab;+ else if (t.dataset.seg) S.sel[t.dataset.seg] = +t.dataset.i;+ else if (t.dataset.sw) S.sw[t.dataset.sw] = S.sw[t.dataset.sw] ? 0 : 1;+ else {+ const a = t.dataset.act, i = +t.dataset.i;+ if (a === "side") S.side = i; else if (a === "layout") { S.layout = i; S.part = 0; } else if (a === "part") S.part = i;+ else if (a === "lfo") S.lfo = i; else if (a === "seqkind") S.seqKind = i; else if (a === "dly") S.dlyOn = S.dlyOn ? 0 : 1;+ }+ render();+});+document.addEventListener("dblclick", e => {+ const k = e.target.closest("[data-k]"); if (!k || k.dataset.k === "morph") return;+ P[k.dataset.k][S.side] = BIP.has(k.dataset.k) ? .5 : P[k.dataset.k][1 - S.side]; render();+});+let drag = null;+document.addEventListener("pointerdown", e => {+ const k = e.target.closest("[data-k],[data-sl]"); if (!k || e.button !== 0) return;+ const id = k.dataset.k || k.dataset.sl;+ drag = { id, y: e.clientY, x: e.clientX, v: id === "morph" ? S.morph : val(id), h: !!k.dataset.sl };+ S.drag = id; e.preventDefault();+});+document.addEventListener("pointermove", e => {+ if (!drag) return;+ const z = +document.getElementById("zL").style.zoom || 2;+ const d = drag.h ? (e.clientX - drag.x) / z / 120 : (drag.y - e.clientY) / z / 140 * (e.shiftKey ? .2 : 1);+ const v = Math.min(1, Math.max(0, drag.v + d));+ if (drag.id === "morph") S.morph = v; else P[drag.id][S.side] = v;+ render();+});+document.addEventListener("pointerup", () => { if (drag) { drag = null; S.drag = null; render(); } });+function pg(id, f) {+ const g = document.getElementById(id);+ g.addEventListener("click", e => { const b = e.target.closest("button"); if (!b) return; g.querySelectorAll("button").forEach(x => x.classList.toggle("on", x === b)); f(b.dataset.v); render(); });+}+pg("pgTheme", v => S.theme = v);+pg("pgZoom", v => { document.getElementById("zL").style.zoom = v; document.getElementById("zS").style.zoom = v; });+pg("pgMorph", v => S.morph = +v);+pg("pgDly", v => { S.dlyOn = +v; S.tab = 5; });++// ---- annotations per tab -------------------------------------------------------------------+const ANN = {+ "Whole card": [+ "<b>Status line removed.</b> It repeated the header badge (voices) and the side switch; its 18 px go to every tab, which is what most tabs lacked.",+ "<b>Tab row decluttered.</b> “Parts” button removed (its controls now live in Voice → Part); Single | Layer | Split stays, Lower | Upper appears only when the patch is layered or split. Nothing is clipped at 700.",+ "<b>Morph column tightened.</b> A strip with A and B at its ends shows where the morph sits and which side is edited; A → B, B → A, Swap become ghost actions (16 tall) instead of three full raised buttons.",+ "<b>Rows line up.</b> Every section uses the same order: header 16 → graph or chooser → knob row → knob row → slider rows. Knob rows of neighbouring sections share a baseline.",+ "<b>“›” chevrons between sections removed.</b> Sections are divided by the Rule only.",+ ],+ Osc: [+ "Each source gets a full-width wave graph (34 tall, draggable as US7 asks) instead of the 56 × 16 thumbnail in the corner.",+ "<b>Filter balance is a slider with end words</b> “multi … ladder” (was a knob reading “Filter · ladder”). Same param, same range.",+ "Noise gets a colour-tilt graph so the three columns read as one row of sources.",+ ],+ Filter: [+ "<b>Mode is a slider with four marks</b> LP · BP · HP · notch (was a knob). The param is continuous and morphs between modes, so it stays a value control — but its readout names the region instead of a lone word under a knob.",+ "<b>Route is a series ↔ parallel slider plus a small route diagram</b> (was a knob reading “parallel”). Brute and Drive sit under it.",+ "Slope 12 / 24 stays in the Ladder header; Cutoff and Resonance are main knobs (44) in both filters, Key and Env teal (34).",+ "Response fills the column: combined curve in viz ink, multimode teal, ladder blue, active node accent only.",+ ],+ Env: [+ "<b>Attack, Decay, Sustain, Release become four labelled drag cells</b> under each graph — the single “1 ms · 91 ms · 50 % · 39 ms” string had no names.",+ "Graphs are taller (70) and the same size in all three envelopes; Velocity / Curve (Delay / Velocity on Mod env) sit centred below.",+ ],+ LFO: [+ "LFO 1 · 2 · 3 picker moves into the section header; shape segments run full width; Sync, Retrig and Voice / Global share one row.",+ "Rate (or Division while synced), Fade and Amount are one row of main knobs; the graph grows to 258 × 166 with a live phase line.",+ ],+ Matrix: [+ "<b>Rows are 20 tall</b> (were ~28), so seven routes show instead of five. Column heads name Source, Destination and the edited side’s depth.",+ "<b>Depth is a centre-zero teal bar</b> with the other side’s depth as a faint tick, plus a mono value — a row of small knobs read as clutter.",+ ],+ FX: [+ "<b>An effect that is off greys out its body</b> (Inactive): Delay’s Sync and Ping-pong no longer glow orange while Delay itself is off.",+ "Each effect gets a 40 px preview (sweep, taps L / R, tail) so the three columns are balanced; knobs grow to 44.",+ "“Section · Effects” becomes a narrow “All” column with a one-line hint of what turning it off means.",+ ],+ Seq: [+ "Header row: on, Seq | Arp, Plays (Layer / Split only). Toolbar: pattern 1–8, length, rate, swing, transpose, latch — Record and To clip at the right.",+ "Grid 594 × 78 with chords, velocity foot, playing step (accent subtle) and selected step (accent outline); the motion lane is its own 26 px strip under it.",+ "Selected-step readout and Rest / Tie sit on the last row with the hint that used to live in the status line.",+ ],+ Voice: [+ "<b>Bend range is a segmented choice</b> ±2 · ±5 · ±12 · ±24 (was a knob with four positions).",+ "<b>Detune is inactive outside Unison</b>, with a hint saying why.",+ "In Layer / Split, Output becomes the <b>Part</b> section: Volume, Pan, Octave, Split key with Learn, voice share, Bend.",+ ],+};+document.getElementById("ann").innerHTML = Object.entries(ANN).map(([k, v]) => `<div><h3>${k}</h3><ol>${v.map(x => `<li>${x}</li>`).join("")}</ol></div>`).join("");+document.getElementById("zL").style.zoom = 2; document.getElementById("zS").style.zoom = 2;+render();+</script>+</body>+</html>diff --git a/specs/055-morph-poly-synth/plan.md b/specs/055-morph-poly-synth/plan.mdnew file mode 100644index 00000000..f9e40a73--- /dev/null+++ b/specs/055-morph-poly-synth/plan.md@@ -0,0 +1,171 @@+# Implementation Plan: Nota Twin — a morphing two-filter analog poly++**Branch**: `feat/morph-poly-synth` | **Date**: 2026-10-30 | **Spec**: [spec.md](spec.md)++**Input**: Feature specification from `specs/055-morph-poly-synth/spec.md`++## Summary++A new built-in instrument, **Nota Twin (kind 18)**: up to 12 analog-modelled voices — two+polyBLEP oscillators with a continuous Wave and a wavefolding Metal, noise, a new+Steiner-Parker-style multimode filter and the shared ladder, a series ↔ parallel route, Brute+feedback, three envelopes, three LFOs and seeded drift. Every sound parameter has an **A and a+B value per part**, exposed as separate plugin-params (`lo.a.cut1`, `lo.b.cut1`), so the+**Morph** between them — and automation that writes to the edited side — uses the existing+param, automation, preset and undo machinery unchanged. A 64-slot matrix per part, eight+macros, an internal FX chain built from Nota's Chorus / Flanger / Phaser / Delay / Reverb+devices, a transport-locked polyphonic **sequencer / arpeggiator** with motion lanes (pattern+data as an immutable snapshot, edited through the existing instrument action channel), and+**Single / Layer / Split** with the 12 voices shared between two parts. One new C ABI function.+Delivered in three slices (P1 → P2 → P3), each a shippable state. Decisions: [research.md](research.md).++## Nota: Read Before Planning++Consulted: [`ARCHITECTURE.md`](../../ARCHITECTURE.md) AR-4/5/6/7/9; the `nota-instrument`+skill (DSP class, registration, card design); [`DESIGN.md`](../../DESIGN.md) + `nota-design`+for the card; [`CONTRIBUTING.md`](../../CONTRIBUTING.md) for headers and dependencies.++## Technical Context++**Language/Version**: C++20 (engine DSP, registration, C ABI); C# / .NET 10 (interop, catalog,+presets, MCP, Remote, device card in Avalonia).++**Primary Dependencies**: none new. Reuses `pentad::` oscillator core + HIIR decimators+(already a listed dependency, fetched by CPM for Pentad / Consort), `dsp::LadderFilter`, `dsp::SvfFilter` (fallback),+`dsp/poly` voice management, and the Chorus / Flanger / Phaser / Delay / Reverb devices.++**Storage**: project file and presets as for other built-ins — normalized params by id;+Twin adds a pattern block to its state blob and to its presets' `StateBase64` (research R11).++**Audio-Thread Impact**: new per-voice DSP in `render()`, allocation-free after construction+(voices, FX devices, matrix tables, pattern storage pre-sized; the delay / reverb buffers are+allocated in the constructor like Consort's). Param values arrive as atomics through the+plugin-param interface; pattern edits publish an immutable snapshot (AR-5) the audio thread+picks up with an atomic pointer load; retired snapshots are freed on the message thread+(RackCore scheme). Musical time only from `setTransport` / `TransportInfo` (AR-9). No locks,+no I/O.++**Testing**: `tests/Nota.SmokeTest` (new Twin section, contract items 1–5); render-comparison+tests on deterministic (seeded) output; `tests/perf/nota_perf.cpp` scenarios+(`instrument-18`, `twin-full-12`, `twin-layer-6x6`, `pentad-full-16`) and+`scripts/perf-gate.sh` for the shared-ladder change; managed unit tests where the preset+remap / "To clip" logic lives.++**Target Platform**: macOS (arm64 + x86_64), Windows x64, Linux x64 — as every built-in.++**Project Type**: desktop app (native engine + managed app).++**Performance Goals**: SC-001 — 12 voices, everything on, no dropouts at 128 samples on the+reference Mac and ≤ 2 × Pentad at 16 voices; SC-006 — idle ≈ empty track; SC-009 — step onsets+on the sample grid.++**Constraints**: append-only param order and action / scope ids; per-voice morph without+per-sample param interpolation (R3); ≤ 1 050 params must not slow the app's param lists (R2a).++**Scale/Scope**: ≈ 5–6 k lines of engine C++ (Consort ≈ 2.3 k is the reference for one+voice architecture; Twin adds parts, matrix, sequencer), one large device card, ≥ 40 presets,+≈ 38 registration sites.++## Constitution Check++*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*++| Principle | Status | How |+|-----------|--------|-----|+| I. Real-time safety | ✅ | pre-sized everything; params as atomics; patterns as immutable snapshots (AR-5); no lock / alloc / I/O in `render()`; transport from `setTransport` (AR-9) |+| II. Boundary discipline | ✅ | one new C function `nota_engine_add_twin_track`; everything else through existing generic param / action / state / scope calls; no JUCE |+| III. Licensing | ✅ | no new dependency; HIIR is already a listed dependency (`LICENSES/third-party.md`); every new file gets the two-line SPDX header; no Arturia names or material |+| IV. Verification gate | ✅ | smoke test extended (5 contract checks); perf scenarios added |+| V. One logical change per PR | ⚠️ → ✅ | the feature is large: shipped as **three PRs**, one per slice (P1 / P2 / P3), each green and usable on its own; the ladder 12 dB tap ships with P1 (no other instrument uses that primitive) |+| VI. Docs in sync | ✅ | CHANGELOG, FEATURES.md (`nota-features`), user docs EN + RU (`nota-docs`), shortcuts if the card adds any (`nota-shortcuts`) — per slice |+| VII. Spec-first | ✅ | this spec / plan / tasks |+| VIII. Rules not weakened | ✅ | no exceptions requested |++**Post-design re-check (after Phase 1)**: still passes. The design added no ABI beyond the one+function, no shared mutable state with the audio thread beyond atomics and snapshots, and the+param-per-side model keeps automation / undo inside existing mechanisms.++## Delivery slices++| Slice | Stories | Ships | PR |+|-------|---------|-------|----|+| 0 | — | `LadderFilter` 12 dB tap — no instrument uses the primitive yet, so it ships with P1 | (in PR 1) |+| P1 | US1, US2, US3 | Twin with one part: voice, A/B morph, expression, fixed routes, a first card (Osc · Filter · Env · LFO · Morph strip, pad), ~12 starter presets, kind registration everywhere, smoke + perf | PR 1 |+| P2 | US4, US5, US6, US7 | 64-slot matrix + macros, FX section, ≥ 40 presets, full card (Matrix · FX tabs, S size, graphs, themes), MCP `read_twin` / `set_twin_route` / side tools | PR 2 |+| P3 | US8, US9 | sequencer / arp / motion lanes / patterns in presets / "To clip"; Lower / Upper parts, Split / Layer, voice share, load-into-part; MCP pattern tools | PR 3 |++The **param layout is designed for P3 from P1**: P1 already declares both parts and both sides+(Upper silent in Single) so no P1 project needs migration — later slices only append.++## Project Structure++### Documentation (this feature)++```text+specs/055-morph-poly-synth/+├── spec.md+├── plan.md # this file+├── research.md # R1–R15 decisions+├── data-model.md # params, routes, patterns, state blob+├── quickstart.md # validation guide+├── contracts/+│ ├── c-abi.md # new ABI function, action ids, scope layout, smoke contract+│ └── mcp-tools.md+├── checklists/requirements.md+└── tasks.md # /speckit-tasks+```++### Source Code (repository root)++```text+src/native/nota.engine/+├── include/nota/nota_engine.h # + nota_engine_add_twin_track+├── src/abi/nota_engine_track.cpp # + the ABI function+├── src/engine/Engine.h, Engine_Devices.cpp # add track, clone, makeBuiltinInstrument+├── src/devices/DeviceFactory.cpp # kind 18+├── src/devices/racks/RackCore.{h,cpp} # makeInstrument kind 18+├── src/devices/instruments/+│ ├── Twin.h / Twin.cpp # instrument: params, parts, voice pool, render, state+│ ├── TwinVoice.h / TwinVoice.cpp # one voice: oscs, Metal, mixer, filters, Brute, envs+│ ├── TwinMod.h / TwinMod.cpp # morph evaluation, matrix, LFOs, sources/dests tables+│ └── TwinSeq.h / TwinSeq.cpp # patterns snapshot, sequencer, arp, motion (P3)+├── src/dsp/primitives/+│ ├── SteinerFilter.h / .cpp # new multimode filter (R5)+│ └── LadderFilter.h / .cpp # + 12 dB tap (slice 0)+├── src/devices/midi_fx/Arpeggiator.* # factor note-order helper if needed (R10)+└── CMakeLists.txt++src/managed/+├── Nota.Infrastructure/Interop/NativeMethods.Tracks.cs, NotaEngine.Tracks.cs+├── Nota.Infrastructure/Persistence/+│ ├── FactoryPresetCatalog.cs # Twin presets (+ TwinSeq text form)+│ ├── PresetService.cs # Twin: NamedParams + pattern StateBase64; load into part+│ └── ProjectService.cs+├── Nota.Infrastructure/Audition/PresetAudition.cs+├── Nota.Application/Engine/IAudioEngine.cs+├── Nota.Application/Palette/BuiltinDeviceCatalog.cs, DeviceCategories.cs+├── Nota.Application/Twin/ # side / part copy, pattern → clip (pure logic, unit-testable)+├── Nota.Presentation/DeviceInsertService.cs, Racks/RackKeyParams.cs+├── Nota.App/DeviceCards/InstrumentCardFactory.cs+├── Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs # the card (tabs, A/B, parts)+├── Nota.App/Controls/TwinViews.cs # waveform, dual-filter response, matrix grid, step grid, pad+├── Nota.App/DeviceCards/Rack/*, DeviceChainView.Shell.cs, NotaDocs.cs, PreferencesWindow.cs, Theme/NotaGeometry.cs+├── Nota.Mcp/Tools/InstrumentTools.cs (+ TwinTools.cs)+└── Nota.Remote/RemoteParams.cs++tests/+├── Nota.SmokeTest/Program.cs (+ TwinTests.cs)+└── perf/nota_perf.cpp+```++**Structure Decision**: one instrument split across four engine translation units (instrument+/ voice / modulation / sequencer) so each slice touches its own files; managed logic that is+not view code (side copy, part remap, pattern → clip) goes to `Nota.Application/Twin/` so it is+unit-testable without the UI. Every registration site mirrors Consort's.++## Complexity Tracking++| Violation | Why Needed | Simpler Alternative Rejected Because |+|-----------|------------|-------------------------------------|+| ~1 050 params on one instrument (others ≤ 160) | per-side params are what makes FR-024 (automation per side), presets, undo and CV work with no new mechanism | a hidden B-side blob would need a parallel automation / undo / preset path for side B |+| Three PRs for one feature (Principle V) | P1 alone is a full instrument; P3's sequencer and parts are each large | one PR would be unreviewable; finer splits would ship unplayable intermediate states |diff --git a/specs/055-morph-poly-synth/quickstart.md b/specs/055-morph-poly-synth/quickstart.mdnew file mode 100644index 00000000..f03a466a--- /dev/null+++ b/specs/055-morph-poly-synth/quickstart.md@@ -0,0 +1,66 @@+# Quickstart: validating Nota Twin (specs/055)++How to prove each slice works. Interfaces: [contracts/c-abi.md](contracts/c-abi.md),+[contracts/mcp-tools.md](contracts/mcp-tools.md); params: [data-model.md](data-model.md).++## Prerequisites++- Release engine build in `src/native/nota.engine/build` (never `-O0` there: a debug engine+ hangs and xruns).+- macOS reference machine for SC-001; Linux with valgrind for the perf gate.++## 1. Build and smoke (every slice)++```bash+scripts/build.sh+```++Green = the engine builds, the app builds, and `tests/Nota.SmokeTest` passes including its+Twin section (contract § Behavioural contract, items 1–5 as their slice lands).++## 2. CPU budget (SC-001, SC-010)++```bash+src/native/nota.engine/build/nota_perf list | grep -i "twin\|pentad"+```++```bash+src/native/nota.engine/build/nota_perf run twin-full-12 5+```++```bash+src/native/nota.engine/build/nota_perf run pentad-full-16 5+```++The generic `instrument-18` scenario (one track, short chords) is added with the kind; the two+`*-full-*` scenarios are new: a sustained 12- / 16-note chord with every section on (both+filters, 3 LFOs, 16 routes, all FX for Twin). Expected: Twin at 12 voices (Single) and at 6 + 6 (Layer scenario) ≤ 2 × Pentad's+`wall_ms_per_s` at its maximum polyphony. On Linux, `scripts/perf-gate.sh develop` must not+regress existing scenarios (Twin adds code only; the `LadderFilter` it extends has no other user).++## 3. In the app (P1 slice)++```bash+dotnet run --project src/managed/Nota.App+```++1. `+ Instrument` → Nota Twin. Play a chord: Init sound, level ≈ Volt Init (US1-1).+2. Hold 8 notes; sweep Osc Wave, Mode, Route, both cutoffs — smooth, no clicks (US1-2).+3. Switch the card to B, change cutoff and Wave; sweep Morph — the sound travels; Morph+ endpoints match A / B (US2). Automate `Cutoff · B` — lane name shows the side.+4. KeyLab Essential mk3 (poly AT) or an MPE controller: press one key — only it opens (US3).+5. Record a take with expression, play it back — same sound (US3-4).++## 4. Later slices++- **P2**: Matrix tab — add LFO 3 → Osc 1 Wave and → multimode cutoff (opposite depths), fill+ 64 slots, see "matrix full" (US4). FX on/off and full bypass (US5). Load every factory preset,+ play C major at velocity 100 across Morph — no silence, no clip (SC-004). S ↔ L, four themes (US7).+- **P3**: step-record 4 chords, play at 90 and 174 BPM, transpose by held key, record a Morph+ motion lane, "To clip", sequencer off — the clip sounds the same (US8, SC-009). Split at C3+ with two presets loaded into Lower / Upper, share 4 + 8, hold 6 keys low — 4 sound (US9).++## 5. UI evidence++Card screenshots via the headless Avalonia / in-app capture recipe used for other cards+(`nota-design` skill) — before/after for the PR (`nota-pr` skill).diff --git a/specs/055-morph-poly-synth/research.md b/specs/055-morph-poly-synth/research.mdnew file mode 100644index 00000000..1c847feb--- /dev/null+++ b/specs/055-morph-poly-synth/research.md@@ -0,0 +1,196 @@+# Research: Nota Twin (specs/055)++Phase 0 of the plan. Each entry: **Decision** · **Rationale** · **Alternatives considered**.++## R1 — Instrument kind and registration++- **Decision**: built-in instrument **kind 18**, display name "Nota Twin", registered at every+ site Nota Consort (kind 15) touches (engine factory, clone, `RackCore::makeInstrument`,+ `nota_engine_add_twin_track`, managed interop, `BuiltinDeviceCatalog`, `DeviceCategories`,+ `InstrumentCardFactory`, `PresetService` / `FactoryPresetCatalog`, `ProjectService`,+ `PresetAudition`, MCP `InstrumentTools`, `RemoteParams`, `RackKeyParams`, `NotaDocs`,+ `tests/perf/nota_perf.cpp`, smoke test).+- **Rationale**: 17 (Mosaic) is the highest kind in use; Consort is the newest full-stack+ instrument with a sequencer, ladders and a delay, so its footprint is the most complete+ checklist (`git grep -il consort` lists 38 files).+- **Alternatives**: extending Pentad or Consort — rejected: the A/B-side and part model changes+ their persisted layout and their identity as faithful single-architecture instruments.++## R2 — Parameter model for sides and parts++- **Decision**: every sound parameter exists as **one plugin-param per part per side**, with ids+ `<part>.<side>.<name>` (`lo.a.cut1`, `up.b.o2wave`). Side-less per-part params (`lo.morph`,+ matrix source / destination, voice mode, voice share) use `<part>.<name>`; global params+ (mode, split key, expression pad, sequencer settings) use a bare `<name>`. Param order =+ persisted layout, append-only, as on every built-in.+- **Rationale**: FR-024 wants automation on the *edited side*: a lane on `lo.b.cut1` **is** "Lower ·+ Cutoff · B", so automation, MIDI-learn, macros, CV links, presets ("modified" mark), clone+ and undo all work with no new mechanism. The card writes to whichever side is being edited.+- **Alternatives**: (a) one param per sound control + a hidden B blob — automation could only+ drive one side, contradicting FR-024; (b) exposing only the morphed value — not editable per+ side. Both rejected.+- **Size**: ≈ 120 sound params × 2 sides × 2 parts + 64 routes × 4 fields × 2 parts + globals ≈+ **1 050 params** (Volt 143, Aurora 156). Open risk **R2a**: the automation target picker,+ the Map tab and Nota Remote's param lists enumerate all params; they must filter Twin's to+ the current part / side or group them. Measured in US1's slice before US2 lands (task in+ tasks.md); if a list is slow, it gets a filter, not a different param model.+- **R2a measured (2026-10-30, T016)**: speed is not the problem — reading 965 ids and names+ over the C ABI takes well under a millisecond and Avalonia builds menus lazily. Usability is:+ the automation menu groups one level deep on the text before the last space, so Twin's+ names make ~250 top-level entries (one per island per part × side, plus a group per+ matrix slot), and Nota Remote's Macros screen pages every param by eight — 121 pages. The+ browser's Map tab lists mappings, not params, so it is unaffected. Fixes, both in US2+ (T092, T093): the automation menu nests on " · " first (Lower A › Ladder › Cutoff), the+ matrix slot params are renamed so they group as one "Routing" section per part / side, and+ Remote pages a curated set for Twin (Morph, the pad, the Lower part's side A sound controls)+ instead of all 965.++## R3 — Morph evaluation and per-voice morph++- **Decision**: at control rate (every 32 samples, as Volt's coefficient updates) each part+ computes `v = lerp(A, B, m)` per continuous param **in its musical domain** (linear in+ pitch for cutoff/tune, in log-time for envelope / LFO times, linear for levels and depths);+ stepped params take A for `m < 0.5`, B otherwise. Per-voice morph (matrix → Morph from a+ per-note source) re-evaluates only the ≈ 70 *voice-local* params for that voice; global ones+ (effects, LFOs in global mode) use the part's morph.+- **Rationale**: cheap (12 voices × 70 lerps / 32 samples), click-free (per-sample smoothing of+ the resulting target values already exists in every voice), and exact at the endpoints+ (SC-002: `lerp(A,B,0) == A` bit-exact).+- **As built (US2)**: the lerp runs on normalized values — a Pitch / LogTime param's normalized+ value is already exponential in its unit (cutoff = 20 Hz · 1000^v), so no per-domain math is+ needed. Voice mode, glide and octave are part params, not side params, so no morph position+ can switch the voice mode under held notes.+- **Alternatives**: per-sample morph of all params — 30× the cost for no audible gain;+ morph on normalized 0..1 values — makes cutoff and times sweep unevenly.++## R4 — Oscillators and Metal++- **Decision**: reuse the `pentad::` 4-point polyBLEP / polyBLAMP core (as Consort does). Wave+ = a continuous blend tri → saw → square; Metal = a wavefolder on the triangle path with+ first-order antiderivative anti-aliasing (ADAA) inside the voice's ×2 oversampling. Sync and+ cross-FM run inside the oversampled voice.+- **Rationale**: proven, aliasing-safe core; ADAA keeps folding clean without ×4.+- **Alternatives**: wavetable-based morph (Aurora) — rejected, loses the analog sync / FM+ behaviour; naive fold at ×4 — 2× more expensive.++## R5 — The multimode (Steiner-Parker-style) filter++- **Decision**: a new shared primitive `dsp/primitives/SteinerFilter.{h,cpp}`: a 12 dB/oct+ Sallen-Key-type ZDF core whose input is *distributed* between its LP / BP / HP injection+ points (as the original circuit does), so Mode sweeps continuously LP → BP → HP → Notch+ (Notch = LP + HP injection); diode-pair soft clipping in the feedback path gives the+ dirty resonance and self-oscillation; per-sample linearised saturation, like+ `LadderFilter`.+- **Rationale**: the injection topology is what makes the original's mode morph and its+ character; a ZDF form stays stable under audio-rate FM (FR-003).+- **Alternatives**: the shared `SvfFilter` with mode crossfading — clean, but lacks the+ character the spec asks for; kept as the fallback if the new model misses the CPU budget.++## R6 — The ladder filter++- **Decision**: reuse `dsp::LadderFilter` (4-pole ZDF, self-oscillating, bass compensation+ flag); the 12 dB slope is `process12()`, the same ladder with its output after the second pole.+- **Rationale**: the shared primitive is already tuned. *Found while implementing:* no instrument+ calls it today — Monolith, Consort and Pentad keep their own copies — so the tap cannot change+ their sound (confirmed by a render-hash comparison), and the separate slice-0 PR is dropped.++## R7 — Brute feedback, drive, drift++- **Decision**: Brute = the filter-section output fed back into the filter inputs through a+ one-sample delay and a tanh stage (bounded gain ≤ 1 at max, so it never runs away — Edge Cases).+ Drive = the shared soft-clip. Drift = Pentad's seeded per-voice spread scheme (re-seeded on+ play edges / jumps), so freezes and renders are identical (FR-012, SC-008).++## R8 — Built-in effects++- **Decision**: Twin owns, per part, an internal chain of existing effect devices — **Chorus /+ Flanger / Phaser** (one active, by the Mod-FX type param), **Delay**, **Reverb** — built at+ construction (allocation-free afterwards), like Nota Rhythm's voice FX. Twin's own A/B FX+ params are morphed (R3) and pushed onto the embedded devices' params at block rate.+- **Rationale**: reuse instead of new DSP; tempo sync comes from the Delay device's own sync+ through `setTransport` / `TransportInfo`.+- **Alternatives**: Aurora-style in-house FX — more code; exposing the devices as a user chain —+ their params couldn't morph.++## R9 — Modulation matrix++- **Decision**: **64 slots per part**, each four params `<part>.mN.src`, `<part>.mN.dst`+ (side-less, stepped, indices into append-only source / destination tables), `<part>.a.mN.amt`,+ `<part>.b.mN.amt` (bipolar, morphed). Per-voice sources (velocity, key, pressure, slide,+ bend, per-voice LFOs, envelopes, random-per-note) evaluate per voice; global sources once.+ Hard-wired panel routes (LFO 1 → pitch, filter env → cutoffs, velocity → amp) stay as knobs.+ A full matrix is reported to the card by an empty-slot search (FR-032 acceptance 2).+- **Rationale**: Consort's patch-bay already stores cables as (src, dst, depth) params, so the+ slot model persists, clones and automates like any param. A grid (Volt's 7 × 6) cannot+ reach 64 routes across ~20 sources × ~60 destinations.+- **Cost check**: 64 routes × 12 voices at control rate — negligible; the cost is in voice DSP.++## R10 — Sequencer, arpeggiator and motion data++- **Decision**: sequencer patterns are **structural state**, not params (as Nota Rhythm's+ steps): 8 patterns × up to 64 steps × up to 6 notes, plus 4 motion lanes × 64 values. The+ message thread edits an authoring copy through `nota_track_instrument_action` (existing ABI)+ and publishes an immutable pattern snapshot (`std::shared_ptr`, older ones retired the+ RackCore way) that the audio thread reads — AR-5. A revision counter in `scopeRead` tells the+ card to re-read after an MCP edit. Sequencer *settings* (rate, swing, length, arp mode,+ octaves, gate, on/off, target part) are ordinary global params, so they automate.+- **Clock**: `setTransport` (beat start, samples per beat, playing) — AR-9; steps fire at exact+ sample offsets computed from the beat grid (SC-009); a jump or loop re-aligns at the next+ step and releases sounding sequencer notes. Not rolling → stopped (FR-061; unlike Consort,+ which free-runs).+- **Arpeggiator**: reuses the note-order logic of `midi_fx/Arpeggiator` (factored into a small+ shared helper if it isn't already one) rather than a second implementation.+- **Motion lanes**: a lane targets a param index + is applied as an override of that param's+ sounding value per step (stepped or smoothed), so it acts on the side the param belongs to+ (FR-063 / FR-024).+- **Alternatives**: patterns as params (Consort's 16 steps) — 8 × 64 × 6 notes would add+ ~10 000 params; patterns as a MIDI clip — loses per-patch patterns and transpose.++## R11 — Presets that carry patterns++- **Decision**: Twin presets keep `NamedParams` (so the "modified" mark, specs/048, and+ cross-version loading keep working) and add the **pattern blob** in `StateBase64`;+ `PresetService` applies params first, then the blob. Factory presets with patterns build the+ blob in `FactoryPresetCatalog` from a compact text form (like `ConsortSeq(...)`).+- **"Load into Lower / Upper"**: managed-side remap of the preset's `lo.*` ids to the target+ part's prefix, applied in one undo gesture; a Single preset fills the chosen part and turns+ the patch to Layer (US9 acceptance 4).++## R12 — Voice allocation, Split / Layer++- **Decision**: one 12-voice pool; each part has a contiguous share (`share` param, steps of 2)+ and its own `PolyVoiceManager`-style allocator over its slice, so stealing never crosses+ parts (FR-071). Split routes by key; Layer sends each note to both parts. A share or mode+ change releases surplus voices (never cuts).+- **CPU**: SC-001 / SC-010 budget is the whole instance, so Layer at 6 + 6 costs what Single+ at 12 does.++## R13 — "To clip"++- **Decision**: managed-side: read the active pattern from the state blob, write notes into a+ new MIDI clip on the track through the existing clip / note APIs and motion lanes into+ automation on the lane's param, in one undo step; then switch `seq.on` off. No new ABI.++## R14 — Undo for multi-param edits++- **Decision**: Copy A → B / B → A / swap, copy part, load-into-part and matrix-route create /+ delete are param batches inside **one mix gesture** in the engine's undo history (specs/009+ / 016 mechanism). Pattern edits checkpoint the instrument's state blob into the same history;+ how Nota Rhythm's step edits undo today is checked first in tasks — Twin follows it, or the+ checkpoint is added if Rhythm has none.++## R15 — Verification++- **Decision**: smoke test (`tests/Nota.SmokeTest`) gains a Twin section: add track, render,+ morph endpoints equal side-only renders (SC-002), per-note pressure isolation (SC-005),+ sequencer onset grid at two tempos (SC-009), state round-trip (SC-008). The perf bench+ (`tests/perf/nota_perf.cpp`, `scripts/perf-gate.sh`) gains kind 18 at 12 voices for SC-001 /+ SC-010 against Pentad at 16.++## Open risks carried into tasks++| Risk | Mitigation |+|------|------------|+| R2a — ~1 050 params slow down param lists / pickers | measure in slice P1; group by part / side |+| R5 — Steiner model misses CPU budget | fall back to SVF mode-crossfade, same params |+| SC-001 — 12 voices × ×2 oversampling × 2 filters | control-rate coefficients, SIMD across voices if needed (`dsp/math/Simd.h`) |diff --git a/specs/055-morph-poly-synth/spec.md b/specs/055-morph-poly-synth/spec.mdnew file mode 100644index 00000000..bfc13cff--- /dev/null+++ b/specs/055-morph-poly-synth/spec.md@@ -0,0 +1,549 @@+# Feature Specification: Nota Twin — a morphing two-filter analog poly++**Feature Branch**: `feat/morph-poly-synth`++**Created**: 2026-10-30++**Status**: Draft++**Input**: User description: "Built-in Nota synth modelled on the Arturia PolyBrute 12: a+polyphonic analog-modelling synth (2 VCOs with waveform morphing, Steiner-Parker and ladder+filters, morphing between two sides of a patch, a modulation matrix, MPE / polyphonic+aftertouch, effects)."++*"Nota Twin" is a working name. "PolyBrute", "Morphée" and "FullTouch" are Arturia+trademarks and appear in no user-facing text, preset, or file name; the instrument is+inspired by the PolyBrute's architecture, not a clone of its sound or its factory library.*++## Clarifications++### Session 2026-10-30++- Q: Which side does automation / MIDI-learn of a parameter write to? → A: the side being+ edited, as on the hardware; lanes are labelled with their side (FR-024).+- Q: Own sequencer / arpeggiator, or rely on Nota Arp and clips? → A: Twin gets its own+ polyphonic step sequencer and arpeggiator with motion recording (FR-060 – FR-067, US8).+- Q: Split / Layer built in, or via an Instrument Rack? → A: built in, two parts sharing the+ 12 voices, 6 + 6 by default (FR-070 – FR-075, US9).++### Session 2026-11-06 (PR #406 hand test)++- Q: The route list or a grid for the matrix? → A: a grid, as Nota Consort's patch matrix:+ sources as rows, destinations as columns, a cell is the route; no list view (US4, FR-032).+- Q: How do the sequencer and the arpeggiator start? → A: as in Nota Consort — with the+ transport stopped a held key runs them on their own clock at the project tempo (Seq from its+ first step, transposed by the key; Arp over the held keys); the last key up stops them,+ Latch / Hold keeps them going. While the transport rolls they lock to the song's grid as+ before (FR-061).+- Q: How many factory presets? → A: twice as many — more classic sounds and more creative ones+ (FR-053).++## Nota Context *(fill in — drives plan and tasks)*++**Feature area** *(pick the main one)*:++- [x] Engine (C++, `src/native/nota.engine`) — real-time audio rules apply, see `ARCHITECTURE.md` AR table+- [x] Managed app (C#, `src/managed/*`) — domain, application, infrastructure, presentation+- [x] UI (Avalonia, `src/managed/Nota.Presentation`) — follow `DESIGN.md` (Studio)+- [ ] Plugin hosting (`pluginhost/`) — the only place JUCE is allowed+- [ ] Build / packaging / CI (`scripts/`, `.github/`) — see `BUILD.md`+- [ ] Docs only++**Nota docs to keep in mind** *(links relative to `specs/<slug>/`, where this file lands)*:+[`ARCHITECTURE.md`](../../ARCHITECTURE.md) (AR rules),+[`CONTRIBUTING.md`](../../CONTRIBUTING.md) (licensing, dependency policy, PR+expectations), [`BUILD.md`](../../BUILD.md), [`DESIGN.md`](../../DESIGN.md),+[`FEATURES.md`](../../FEATURES.md). Built the way the `nota-instrument` skill describes;+Nota Volt, Aurora, Pentad and Consort are the closest existing instruments.++**Where it sits among the existing synths**: Volt is the everyday subtractive default, Pentad+the Prophet-style 5-voice poly, Consort the paraphonic ladder synth, Flux the XY "timbre+worlds" morph. Twin's own ground is the **whole-patch A↔B morph** over a **two-filter+(multimode + ladder) analog voice** with **per-note expression everywhere** — a "big poly"+for evolving pads, expressive leads and keys that change character under the hand.++## User Scenarios & Testing *(mandatory)*++### User Story 1 - Play a rich analog poly (Priority: P1)++A producer adds Nota Twin to an instrument track and plays chords. Each voice has two+oscillators whose waveform sweeps continuously (saw ↔ square ↔ triangle, with a wavefolding+"metal" colour on the triangle), noise, and two filters — a multimode (LP/BP/HP/Notch, swept+continuously) and a 24/12 dB ladder low-pass — that can run in series, in parallel, or anywhere+between. Three envelopes (filter, amp, mod) and three LFOs shape the sound. Up to 12 voices+play at once, with Poly, Mono and Unison modes, glide and a per-voice analog drift.++**Why this priority**: Without a good-sounding voice nothing else matters; this alone is a+usable new instrument.++**Independent Test**: Add Twin, play a held 8-note chord from Init, sweep each oscillator's+Wave, the filter mode, the series/parallel balance and both cutoffs; every move is heard+smoothly, without clicks or zipper noise, and no voice drops.++**Acceptance Scenarios**:++1. **Given** a new Twin at Init, **When** the user plays a note, **Then** a plain, in-tune+ saw-through-ladder sound plays, and its level matches Volt's Init within ±1.5 dB.+2. **Given** a held chord, **When** the user sweeps any oscillator Wave, the multimode filter's+ mode, or the filter routing balance, **Then** the timbre changes continuously with no step,+ click or level jump greater than 1 dB.+3. **Given** 13 notes held in Poly with 12 voices, **When** the 13th note arrives, **Then** the+ quietest / oldest voice is taken over without a click and the other 11 keep sounding.+4. **Given** oscillator sync, cross-FM (Osc 2 → Osc 1), filter FM from an oscillator and the+ "brute" feedback/drive control, **When** each is turned up, **Then** it adds the expected+ harshness (sync sweep, metallic sidebands, growl) and stays bounded — no runaway level.+5. **Given** Unison, **When** one key is played, **Then** all available voices stack on it,+ detuned and spread across the stereo field by the Spread control.++---++### User Story 2 - Morph between two sides of a patch (Priority: P1)++Every patch has an **A side** and a **B side**. The user dials a sound on A, switches the+editor to B, turns knobs to make the second sound, and then the **Morph** control sweeps the+whole patch between them — every continuous parameter interpolates at once (oscillators,+filters, envelopes, LFOs, effect amounts, modulation depths). Morph is an ordinary parameter:+it can be automated, mapped to a macro, MIDI-learned, CV-modulated in the Modular View, and is+itself a modulation-matrix destination (so an LFO, the mod wheel or a note's pressure can+morph).++**Why this priority**: It is the instrument's defining idea; without it this is "another+two-oscillator poly".++**Independent Test**: Make A a dark pad and B a bright pluck, automate Morph 0 → 1 over 4+bars, render: the sound travels continuously from one to the other, and Morph = 0 and = 1+render identically to A and B played alone.++**Acceptance Scenarios**:++1. **Given** the editor showing A, **When** the user turns a knob, **Then** only A's value+ changes; switching to B shows B's own value, and each knob also shows where the morphed+ (current) value sits between A and B.+2. **Given** Morph at 0.5, **When** a note plays, **Then** every continuous parameter sounds+ halfway between its A and B values (on the parameter's musical scale — cutoff in pitch, times+ logarithmically), and stepped parameters (wave-type switches, voice mode, LFO sync on/off)+ switch at the midpoint without a click.+3. **Given** a side, **When** the user picks "Copy A → B" (or B → A), **Then** both sides+ become equal and the morph is silent until something is changed — one undo step.+4. **Given** a modulation route whose depth differs between A and B, **When** Morph moves,+ **Then** the depth moves too.+5. **Given** Morph driven from the matrix by pressure, **When** each note is pressed harder,+ **Then** that note alone morphs toward B (per-voice morph), the other held notes don't.++---++### User Story 3 - Play it expressively (Priority: P1)++The instrument responds to everything a player's hands produce: velocity, channel+aftertouch, polyphonic aftertouch, MPE (per-note bend, pressure, slide), the mod wheel, pitch+bend, and the sustain pedal — and a three-axis **expression pad** on the card (X, Y and a+pressure axis Z) gives mouse/touch players the same expression. Each of these is a source in+the modulation matrix, and sensible defaults are routed out of the box (pressure → morph or+cutoff, slide → multimode cutoff, mod wheel → LFO 1 vibrato).++**Why this priority**: The PolyBrute is played, not programmed; per-note expression is what+makes the morph musical. Nota already carries MPE and poly aftertouch end-to-end, so the cost+is in routing, not plumbing.++**Independent Test**: With an MPE controller (or the Arturia KeyLab's poly aftertouch / the+phone's Expressive keys), hold a chord and press one key harder — only that note opens; slide+one finger — only that note's filter moves; recording keeps the per-note curves and the+playback sounds the same.++**Acceptance Scenarios**:++1. **Given** an MPE controller, **When** the user bends one note of a chord, **Then** only that+ voice's pitch moves, over the controller's announced bend range.+2. **Given** an ordinary keyboard with polyphonic aftertouch, **When** one key is pressed+ harder, **Then** only that voice receives the pressure; with channel aftertouch, all voices do.+3. **Given** the card's expression pad, **When** the user drags across it and holds the mouse+ (or presses harder on a touch surface), **Then** X, Y and Z move their matrix routes live+ and can be recorded as automation.+4. **Given** a recorded clip with per-note expression, **When** it plays back, **Then** Twin+ sounds the same as during the take.++---++### User Story 4 - Route modulation in a matrix (Priority: P2)++A sound designer opens the Matrix tab: a grid, as on Nota Consort, with sources as rows (3+LFOs, mod envelope, filter and amp envelopes, velocity, key, pressure, slide, per-note bend, mod+wheel, expression pad X/Y/Z, random-per-note, macros) and destinations as columns (any+oscillator, mixer, filter, envelope, LFO, morph and effect amount). Dragging a cell creates the+route and sets its bipolar depth on the side being edited; double-click removes it. The grid+shows the rows and columns the routes use, then the last ones picked; clicking a row or column+name puts another source or destination (grouped menus) there. At+least 64 simultaneous routes are possible. A small number of hard-wired routes (LFO → pitch,+env → cutoff, velocity → amp) remain as panel knobs so common patches need no matrix work.++**Why this priority**: Deep modulation is the second pillar of the instrument, but US1–US3+already play well with the fixed routes.++**Independent Test**: Route LFO 3 to Osc 1 Wave and to the multimode cutoff with opposite+depths, verify both move in opposite directions; remove one route, verify only it stops.++**Acceptance Scenarios**:++1. **Given** the matrix, **When** the user creates a route, sets its depth and deletes it, **Then**+ each step is one undo step and the sound follows immediately.+2. **Given** 64 routes in use, **When** the user tries to add one more, **Then** the editor says+ the matrix is full instead of silently dropping it.+3. **Given** a route depth, **Then** it is itself automatable and differs per A/B side (US2).++---++### User Story 5 - Finish the sound with its own effects (Priority: P2)++A built-in, switchable effects section follows the voices: a **modulation** effect (chorus,+flanger, phaser, ensemble), a **delay** (tempo-syncable, ping-pong) and a **reverb**, each with+its own on/off, mix and two or three character controls, and each part of the A/B morph. The+section can also be bypassed entirely so Nota's own effect devices can be used instead.++**Why this priority**: Presets need effects to sound finished, but Nota's effect devices+already cover the need, so this is polish over the instrument, not its core.++**Independent Test**: Turn each effect on and off on a held chord; bypass the whole section;+morph between an A side with a dry sound and a B side with a long reverb.++**Acceptance Scenarios**:++1. **Given** the effects section off, **Then** the output equals the voice sum alone.+2. **Given** a tempo-synced delay, **When** the project tempo changes, **Then** the delay time+ follows.+3. **Given** a long reverb or delay tail, **When** notes stop, **Then** the tail rings out and the+ instrument only goes to sleep once the tail is silent.++---++### User Story 6 - Start from presets (Priority: P2)++Twin ships with a factory library of at least 40 presets across folders (Pads, Keys, Leads,+Bass, Brass, Strings, Plucks, Sequence, FX, Morph showcases), each using A/B morph meaningfully+and assigning the macros. User presets save and load both sides, the matrix and the effects, and+the preset name / "modified" mark work as on every other device (specs/048).++**Why this priority**: Most users will meet the instrument through its presets.++**Independent Test**: Load each factory preset, play a C-major chord across the morph range;+every preset makes sound, none clips beyond 0 dBFS at velocity 100, none is silent on either side.++---++### User Story 7 - See and edit it on a device card (Priority: P2)++The device card follows the Studio design language and the signal-chain layout of Volt and+Aurora: a large size with tabs (Osc · Filter · Env · LFO · Matrix · FX · Seq), a Lower / Upper part switch when the patch is a Split or Layer, and a small size with the+Morph control, the A/B switch, the expression pad and the key sound knobs. Graphs are+interactive: the waveform of each oscillator, the two filters' combined response, envelope+shapes and LFO shapes can be dragged. The A/B side being edited is always obvious.++**Independent Test**: Edit a full patch using only the card; resize S ↔ L; verify the A/B side+indicator, live morph position and per-knob A/B markers in both sizes, in all four colour themes.++---++### User Story 8 - Sequence it from the instrument itself (Priority: P3)++A player enters a 16-step chord pattern by holding chords on the keyboard in step-record, then+holds a key: the pattern runs at the project tempo from its first step, transposed by the key,+and stops when they let go (Latch keeps it). With the transport playing it runs in time with+the song; holding a key transposes it live. They+arm motion recording, sweep Morph and the multimode cutoff over one pass — the moves now+repeat with the pattern. Switching between the patch's 8 patterns happens at the pattern end.+When they like it, "To clip" writes the pattern into a MIDI clip on the track. The+arpeggiator is the quick alternative: hold a chord, pick Up/Down, 2 octaves, 1/16.++**Why this priority**: It is the PolyBrute's performance workflow and makes presets come+alive, but Nota's clips, automation and Nota Arp already let users sequence Twin, so it+follows the sound engine.++**Independent Test**: Step-record a 4-chord pattern, play it with the transport at two tempos,+transpose by a held key, record one motion lane, convert to a clip, switch the sequencer off:+the clip plays the same notes.++**Acceptance Scenarios**:++1. **Given** step-record armed, **When** the user holds a three-note chord and releases it,+ **Then** that step holds the three notes and the cursor moves to the next step.+2. **Given** a running pattern, **When** the transport tempo changes or the transport stops,+ **Then** the sequencer follows / stops and no note hangs.+3. **Given** a motion lane recorded on Morph, **When** the pattern repeats, **Then** Morph+ follows the recorded moves (stepped or smooth per the lane's setting), and the user's own+ move of the knob takes over until they let go.+4. **Given** a pattern, **When** the user picks "To clip", **Then** a MIDI clip with the+ pattern's notes and velocities appears (motion lanes as automation) — one undo step.+5. **Given** the arpeggiator in Hold, **When** the user plays a new chord, **Then** the+ arpeggio switches to it on the next step.++---++### User Story 9 - Split or layer two sounds (Priority: P3)++A keyboardist puts a bass on the lower half and a pad on the upper half (Split at C3), or+stacks a string patch with a bell patch on every key (Layer), each part with its own morph,+and balances the 12 voices between them (e.g. 4 for the bass in Mono, 8 for the pad). They+load two existing presets into the two parts rather than building both from scratch.++**Why this priority**: Valuable for live playing and for "combination" presets, but an+Instrument Rack with two Twins already gives a workable split, so it comes last.++**Independent Test**: Make a Split at C3 with two different presets loaded into Lower and+Upper; play across the split; change the share to 4 + 8 and verify each half's polyphony.++**Acceptance Scenarios**:++1. **Given** Split at C3, **When** the user plays B2 and C3, **Then** B2 sounds the Lower part+ and C3 the Upper.+2. **Given** a 4 + 8 share, **When** 6 keys are held in the Lower half, **Then** only 4 sound+ (oldest stolen within Lower) and the Upper part keeps its 8.+3. **Given** Layer, **When** one key is played, **Then** both parts sound it, each through its+ own morph, matrix and effects.+4. **Given** a Single patch, **When** the user loads a preset into Upper, **Then** the patch+ becomes Layer with the current sound as Lower — one undo step.+5. **Given** the mode changes while notes are held, **Then** held notes release normally; no+ note hangs.++---++### Edge Cases++- **Morph between stepped values** (e.g. A uses ladder 24 dB, B 12 dB; A Poly, B Unison): they+ switch at the midpoint; the voice-mode switch never cuts held notes off.+- **Voice count changes while notes are held** (12 → 6): the extra voices release, not cut.+- **Self-oscillating filters with high resonance on both sides of the morph**: level stays+ bounded (soft-limited) through the whole morph range.+- **Extreme cross-FM / sync / feedback at high notes**: aliasing is kept inaudible at 44.1 kHz+ and above; the output never contains NaN or inf (it recovers if an input does).+- **MPE and a regular keyboard on the same track at once**: channel-wide controls move all+ voices, per-note ones only their note, as on Nota's other MPE instruments.+- **Sample-rate change or offline render at another rate**: the patch sounds the same, drift+ included (seeded, so a freeze and a render are identical).+- **Loading a project saved by a newer Twin with more parameters**: unknown values are ignored,+ missing ones take their defaults, the patch still loads.+- **Cloning the track, copy/paste of the device, freeze / bounce, Instrument Rack chains**: both+ sides, the matrix and the effects come along.+- **Idle**: with no notes and no tail, the instrument costs (near) nothing — a stopped+ sequencer included.+- **Automation recorded on side B while Morph = 0**: it is stored and plays, but is not heard+ until Morph moves toward B; the lane name ("· B") makes this explainable.+- **Sequencer running while the user also plays keys**: played notes sound alongside the+ pattern (unless a key is used for transpose with latch off); both share the part's voices.+- **Loop / jump in the transport**: the sequencer re-aligns to the new position at the next+ step without a stuck note.+- **Split with Mono on one part**: legato and glide work within that part only.+- **A preset saved as Single loaded into Upper of a Split**: only its part is taken; its own+ sequencer pattern is kept with it.+- **Voice share changed while both parts are held**: extra voices release, as in voice-count+ changes.++## Requirements *(mandatory)*++### Functional Requirements++**Voice**++- **FR-001**: The instrument MUST provide up to 12 voices per instance (default 12, selectable+ lower to save CPU; shared between parts in Split / Layer, FR-071), with Poly, Mono, Legato and Unison modes, glide (with legato-only option),+ and voice stealing that never clicks.+- **FR-002**: Each voice MUST have two oscillators. Each oscillator's **Wave** control MUST+ morph continuously between triangle, sawtooth and square/pulse, with pulse width and a+ wavefolding **Metal** amount; each MUST have coarse (±2 octaves in semitones) and fine tune.+- **FR-003**: Oscillator 2 MUST be able to hard-sync to oscillator 1, and frequency-modulate+ oscillator 1; an oscillator MUST be able to frequency-modulate the multimode filter's cutoff.+ Oscillator 2 MUST have a low-frequency / keyboard-off option so it can act as a modulator.+- **FR-004**: Each voice MUST have a noise source with a colour control (white ↔ pink/red).+- **FR-005**: A mixer MUST set each source's level and, per source, its balance between the two+ filters' inputs.+- **FR-006**: The **multimode filter** MUST sweep continuously through low-pass, band-pass,+ high-pass and notch (in the Steiner-Parker character: aggressive, dirty resonance), with+ cutoff, resonance up to self-oscillation, key tracking and envelope amount.+- **FR-007**: The **ladder filter** MUST be a low-pass with 12 and 24 dB/oct slopes, cutoff,+ resonance up to self-oscillation (with the ladder's characteristic bass loss), key tracking+ and envelope amount.+- **FR-008**: A routing control MUST blend continuously between series (multimode → ladder) and+ parallel filter routing.+- **FR-009**: A **Brute**/feedback control MUST feed the output back into the filters for+ growl and overdrive, and an output drive MUST saturate softly; both bounded at maximum.+- **FR-010**: There MUST be three envelopes — filter (ADSR), amp (ADSR) and a mod envelope+ with delay and a loop option — each with velocity sensitivity and curves.+- **FR-011**: There MUST be three LFOs with selectable shapes (sine, triangle, saw, square,+ sample & hold, smooth random), rate free or tempo-synced, per-voice or global, retrigger and+ fade-in; LFO 3 MUST additionally offer a drawable curve/symmetry shape.+- **FR-012**: Each voice MUST carry a small, seeded analog drift (pitch, cutoff, envelope+ times) with an amount control, so renders and freezes of the same project are identical.+- **FR-013**: Stereo: voices MUST be spreadable across the stereo field (by voice, by key or+ in unison), with an overall pan and volume.++**Morph**++- **FR-020**: Every sound parameter MUST hold an A value and a B value. A **Morph** control (0 =+ A, 1 = B) MUST set the sounding value of every continuous parameter by interpolating on its+ musical scale; stepped parameters MUST switch at the midpoint.+- **FR-021**: The editor MUST let the user choose which side (A or B) knobs edit, and MUST show+ for each knob both side values and the current morphed position.+- **FR-022**: The user MUST be able to copy A → B, B → A, and swap A ↔ B, each as one undo step.+- **FR-023**: Morph MUST be automatable, MIDI-learnable, macro-assignable, a Modular View CV+ target, and a modulation-matrix destination evaluated per voice.+- **FR-024**: Automation, MIDI-learn, macro and CV moves of an ordinary sound parameter MUST+ write to the **side being edited** when the move is made (as on the hardware), and the+ automation lane MUST say which side it drives ("Cutoff · A" / "Cutoff · B"); a lane on the+ side the morph is away from is heard only in proportion to the morph. Morph itself and the+ expression pad are side-less.++**Expression and modulation**++- **FR-030**: The instrument MUST respond to velocity, release velocity, channel aftertouch,+ polyphonic aftertouch, MPE per-note bend / pressure / slide, pitch bend (selectable range),+ mod wheel and the sustain pedal, honouring Nota's existing MPE conventions.+- **FR-031**: The card MUST offer a three-axis expression pad (X, Y, Z = pressure / hold) whose+ values are automatable parameters and matrix sources.+- **FR-032**: A modulation matrix MUST allow at least 64 simultaneous routes from the sources+ listed in US4 to any continuous sound parameter, with a bipolar depth per route that is itself+ per-side (morphs) and automatable. Per-note sources MUST act per voice.+- **FR-033**: Default routes MUST exist on Init (mod wheel → vibrato, pressure → cutoff, slide →+ multimode cutoff, velocity → amp) and be removable.+- **FR-034**: Eight macros MUST be available, each driving several destinations, as on Volt and+ Aurora.++**Effects**++- **FR-040**: A built-in effects section MUST provide a modulation effect (chorus / flanger /+ phaser / ensemble), a delay (free or tempo-synced, ping-pong) and a reverb, each switchable,+ with mix and character controls that are part of the A/B morph; the whole section MUST be+ bypassable.++**Integration**++- **FR-050**: The instrument MUST appear in the Browser and the command palette like every+ built-in instrument (with role, aliases and a description), be usable on instrument tracks,+ in Instrument Rack chains and through the "Replace…" command.+- **FR-051**: All parameters (both sides, matrix depths, macros, effects) MUST be automatable,+ saved with the project, kept by clone / copy / paste / freeze, and restored by undo.+- **FR-052**: Projects saved with an older Twin MUST load in a newer Twin (parameters are only+ ever appended).+- **FR-053**: A factory library of at least 110 presets (US6) MUST ship; user presets MUST work+ as on other built-in instruments, including the preset name and "modified" mark.+- **FR-054**: The instrument MUST be reachable from the MCP surface at least as far as other+ built-in instruments are (read / set parameters, load a preset).++**Sequencer and arpeggiator**++- **FR-060**: Twin MUST have its own **polyphonic step sequencer**: patterns of 1–64 steps,+ up to 6 notes per step, per-step velocity, gate length and tie, rest steps, rate (1/4 … 1/32+ with triplets), swing, and a pattern length independent of the bar.+- **FR-061**: The sequencer MUST follow the Nota transport (start, stop, position, tempo) while it+ plays. With the transport stopped, a held key MUST run the sequencer (from its first step) or+ the arpeggiator on its own clock at the project tempo, and the last key up MUST stop it and+ release its notes unless Latch (Seq) / Hold (Arp) is on. A held key MUST be able to+ **transpose** the running pattern (root = the pattern's first note), with a latch option.+- **FR-062**: Patterns MUST be enterable by step recording from the keyboard (notes held+ together become one chord step) and by editing steps on the card; one undo step per edit.+- **FR-063**: **Motion recording**: each pattern MUST hold up to 4 motion lanes; recording+ captures a knob's (or Morph's, or the expression pad's) movement per step, played back+ stepped or smoothed. Motion lanes act on top of the patch, per side as in FR-024.+- **FR-064**: An **arpeggiator** MUST offer Up, Down, Up/Down, Random, As Played and Chord+ modes, 1–4 octaves, rate (synced), gate, swing and Hold; the sequencer and the arpeggiator+ are alternatives, not both at once.+- **FR-065**: Each patch MUST store its pattern(s) and arp settings; at least 8 patterns per+ patch MUST be selectable, switching at the next pattern end.+- **FR-066**: The user MUST be able to turn the current pattern into an ordinary MIDI clip on+ the track (notes with velocity; motion lanes as automation), after which Twin's own+ sequencer can be switched off.+- **FR-067**: Sequencer and arp output MUST behave like keyboard notes everywhere downstream+ (voice allocation, Split / Layer routing, per-note expression sources, macros); a MIDI+ effect in front of Twin (e.g. Nota Arp) sees only the incoming notes, not the sequencer's.++**Split / Layer**++- **FR-070**: A patch MUST be able to hold **two parts** (Lower / Upper), each a complete+ sound with its own A/B sides, Morph, matrix, macros and effects section, in one of three+ modes: **Single** (one part, the default), **Layer** (both parts on every key) and **Split**+ (Lower below a split key, Upper from it up).+- **FR-071**: The 12 voices MUST be divided between the parts — default 6 + 6, adjustable in+ steps of 2 (2 + 10 … 10 + 2); each part steals only within its own share. Voice mode+ (Poly / Mono / Unison) and glide are per part.+- **FR-072**: Split MUST have a split key (set by a key press or a value) and a per-part+ octave transpose; Layer MUST have a per-part volume and pan so the balance can be set.+- **FR-073**: The editor MUST make the edited part obvious (Lower / Upper switch alongside+ the A/B switch); automation lanes and parameter names MUST include the part+ ("Upper · Cutoff · A").+- **FR-074**: Performance controls (pitch bend, mod wheel, sustain, aftertouch, MPE, the+ expression pad) MUST reach both parts; the sequencer / arp MUST target Lower, Upper or both.+- **FR-075**: Copy part Lower → Upper (and back) and "load preset into Lower / Upper" MUST+ exist, so two existing presets can be combined into a split or layer.++### Key Entities++- **Patch**: the whole instrument state — mode (Single / Layer / Split), split key, voice+ share, one or two parts, the sequencer patterns and arp settings. Saved as a preset or with+ the track.+- **Part (Lower / Upper)**: a complete sound — side A, side B, the morph position, matrix,+ macros, effects, voice settings.+- **Side (A / B)**: one value for every sound parameter.+- **Modulation route**: source, destination, depth on A, depth on B.+- **Expression state per voice**: velocity, pressure, slide, bend, random seed — the per-note+ inputs that the matrix reads.+- **Factory preset**: a named patch in a folder, with its macro assignments.+- **Pattern**: steps (each: up to 6 notes, velocity, gate, tie / rest), length, rate, swing,+ and up to 4 motion lanes (target parameter and side, one value per step, stepped / smooth).++## Success Criteria *(mandatory)*++### Measurable Outcomes++- **SC-001**: A 12-note chord with both filters, all three LFOs, 16 matrix routes and all+ effects on plays without a single dropout at a 128-sample buffer on the reference Mac, and+ one instance at full polyphony costs no more than 2× Nota Pentad at its maximum polyphony in+ the engine perf gate.+- **SC-002**: Morph = 0 and Morph = 1 renders are identical (bit-exact with drift seeded) to+ renders of a patch holding only side A or only side B.+- **SC-003**: A full Morph sweep (0 → 1 in one beat) on any factory preset produces no click+ or level jump above 1 dB that is not present in A or B themselves.+- **SC-004**: Every factory preset produces sound on both sides, peaks under 0 dBFS at+ velocity 100 with an 8-note chord, and loads in under 50 ms.+- **SC-005**: Per-note expression: pressing one note of a held 6-note chord changes only that+ note's spectrum (others within 0.5 dB of before), verified by an automated render test.+- **SC-006**: With no notes and no effect tail, an instance's CPU cost is indistinguishable+ from an empty track.+- **SC-007**: A user who knows Volt can build a two-sided morphing pad from Init using only the+ card in under 5 minutes (checked in the docs walkthrough).+- **SC-008**: Rendering the same project twice gives identical output; a project round-trips+ through save / load with an identical render.+- **SC-009**: A sequencer pattern stays sample-accurate to the transport: over 64 bars at any+ tempo from 60 to 200 BPM its step onsets drift by no more than one sample from the grid,+ and a pattern converted to a clip renders identically to the running pattern.+- **SC-010**: In Split / Layer at full polyphony (6 + 6) the CPU cost stays within SC-001's+ budget for one instance.+- **SC-011**: At least 8 of the factory presets use the sequencer or arpeggiator and at least+ 6 use Split or Layer.++## Assumptions++- **Inspired by, not cloned**: the target is the PolyBrute's *architecture and playing feel*,+ not a measured match of its circuits or factory sounds; no Arturia names, presets or+ artwork are used. Sound quality is judged by ear and by the success criteria above.+- **No new dependency**: the DSP is built from Nota's own primitives (oscillators, SVF, ladder,+ oversampler, delay, reverb); the Steiner-Parker character is a new in-house filter model.+- **Hardware-only features are out of scope**: the Morphée / ribbon hardware is replaced by+ the on-card expression pad plus the existing MPE / aftertouch / Nota Remote inputs; the+ PolyBrute's front-panel "Panel" mode and its MIDI SysEx patch format are not supported.+- **12 voices** match the original; the voice cap is a CPU choice, not a design one, and can+ rise later.+- **Standalone VST3** (as Pentad has) is a follow-up, not part of this feature.+- The **matrix size** of 64 routes is a target from the original; the plan may confirm a+ different number if per-voice cost requires it, with the spec updated.+- **Delivered in slices**: the scope is large, so the plan delivers it in priority order —+ P1 (voice, morph, expression) is a playable release on its own; P2 (matrix, effects,+ presets, full card) next; P3 (sequencer / arp, Split / Layer) last. Each slice keeps the+ persisted state append-only so patches from an earlier slice load in a later one.+- Nota Remote, the shortcuts list and the user docs are updated as for any new instrument.++## Nota Compliance Checklist *(review before implementation; re-check in tasks.md)*++- [ ] Every new source file will carry the AGPL-3.0-only SPDX header (two lines, see CONTRIBUTING.md)+- [x] No new dependency — or: license checked, AGPL-compatible, `LICENSES/third-party.md` row planned+- [ ] Audio-thread impact considered: no alloc / lock / I/O on the audio thread (AR-6), command queue for data in (AR-4), immutable snapshots for structural edits (AR-5) — the matrix and A/B sides must be pre-allocated; route edits go through the command queue+- [ ] Managed/native crossings go through the pure C ABI in `nota_engine.h` only (AR-7); no JUCE outside `pluginhost/`+- [ ] Smoke-test impact assessed: engine behaviour change → extend `tests/Nota.SmokeTest` (new instrument kind, morph endpoints, per-note expression render)+- [ ] User-visible change → `CHANGELOG.md` `[Unreleased]` entry planned (and FEATURES.md / user docs via the nota-features / nota-docs skills when working with an agent that has them)+- [ ] UI change → follows `DESIGN.md` (Studio design language)diff --git a/specs/055-morph-poly-synth/tasks.md b/specs/055-morph-poly-synth/tasks.mdnew file mode 100644index 00000000..651bc74f--- /dev/null+++ b/specs/055-morph-poly-synth/tasks.md@@ -0,0 +1,378 @@+---++description: "Tasks for Nota Twin — a morphing two-filter analog poly (specs/055)"+---++# Tasks: Nota Twin — a morphing two-filter analog poly++**Input**: Design documents from `specs/055-morph-poly-synth/`++**Prerequisites**: [plan.md](plan.md), [spec.md](spec.md), [research.md](research.md),+[data-model.md](data-model.md), [contracts/c-abi.md](contracts/c-abi.md),+[contracts/mcp-tools.md](contracts/mcp-tools.md), [quickstart.md](quickstart.md)++**Tests**: included — the constitution (IV) requires the smoke test to cover engine behaviour,+and the spec's success criteria (SC-002, SC-005, SC-008, SC-009) are render comparisons. Smoke+checks live in `tests/Nota.SmokeTest/TwinTests.cs` (the per-instrument pattern of+`KeysTests.cs`); perf scenarios in `tests/perf/nota_perf.cpp`.++**Organization**: by user story, inside the three delivery slices of plan.md — slice 0 (shared+ladder PR), **P1 = US1–US3 (PR 1)**, **P2 = US4–US7 (PR 2)**, **P3 = US8–US9 (PR 3)**.++**Engine paths** below are relative to `src/native/nota.engine/`; managed paths to+`src/managed/`. "Mirror Consort" = copy what the same site does for kind 15+(`git grep -n -i consort -- <file>`).++## Format: `[ID] [P?] [Story] Description`++- **[P]**: can run in parallel (different files, no dependency on an unfinished task)+- **[Story]**: US1 … US9 from spec.md++---++## Phase 1: Setup++**Purpose**: branch, empty files, build wiring.++- [X] T001 Create branch `feat/morph-poly-synth` off `develop` (the `nota-pr` skill's branch rule); `.specify/feature.json` already points at `specs/055-morph-poly-synth` — done as worktree `~/repos/nota/nota-twin` (the main checkout is busy with other work); `.specify/feature.json` there points at this spec+- [X] T002 Create empty translation units with the two-line AGPL SPDX header and a *why* comment header: `src/devices/instruments/Twin.{h,cpp}`, `TwinVoice.{h,cpp}`, `TwinMod.{h,cpp}`, `TwinSeq.{h,cpp}`, `src/dsp/primitives/SteinerFilter.{h,cpp}` — done for `Twin.{h,cpp}`; the voice / mod / seq / Steiner files are created with their stories (US1, US4, US8) instead of as empty files+- [X] T003 Add the new `.cpp` files to `CMakeLists.txt` (engine sources list, next to `Consort.cpp`) and confirm the Release build in `build/` still compiles++---++## Phase 2: Foundational (slice 0 + the instrument shell)++**Purpose**: what every story needs — the shared-ladder change, the full param table, kind 18+registered end-to-end. **No user-story work starts before this phase is done.**++### Slice 0 — shared ladder 12 dB tap (own small PR)++- [X] T004 Add a 2-pole (12 dB/oct) output tap to `dsp::LadderFilter` in `src/dsp/primitives/LadderFilter.{h,cpp}` (e.g. `process(x, bassComp, slope12)` defaulting to the current 4-pole path) without changing the existing code path's arithmetic (research R6)+- [X] T005 Verify Monolith, Consort and Pentad renders are bit-identical before/after T004 (render each `instrument-13/14/15` perf scenario's output to WAV at both commits and compare), and run `scripts/perf-gate.sh develop` on Linux — no regression; open the slice-0 PR via the `nota-pr` skill — done: no instrument uses `dsp::LadderFilter` today (Monolith, Consort, Pentad keep their own copies), so the tap cannot change them; a hash harness confirmed Monolith / Pentad / Consort renders (default + high resonance) bit-identical to develop. The Linux perf gate was not run, and the separate slice-0 PR is dropped (the change ships with P1)++### Twin shell++- [X] T006 Define the complete param table in `src/devices/instruments/Twin.h` for **all slices** (data-model.md): globals (`mode`, `splitkey`, `share`, `voices`, `padx`, `pady`, `padz`, `bendrange`, `seq.*`, `arp.*`), per part `lo.` / `up.` side-less params (`morph`, `voicemode`, `glide`, `glidelegato`, `octave`, `vol`, `pan`, `fxon`, `macroN`, `mN.src`, `mN.dst` for N = 1..64), and per part per side `<part>.<a|b>.<name>` for every row of the data-model's per-side table (incl. `mNamt` and FX); an enum + a constexpr descriptor table (id, display name, default, *stepped* flag, musical domain: pitch / log-time / linear) generated from one list so order = persisted layout, **APPEND ONLY**+- [X] T007 Implement the plugin-param interface on `Twin` in `src/devices/instruments/Twin.{h,cpp}` (`pluginParamCount/Id/Name/Get/Set/Text/Default/IndexOfId`, `std::atomic<float> pn_[kNumParams]`), display names that include part and side ("Lower A · Ladder Cutoff" — the automation menu groups on the head before the last space; data-model / FR-073), `kind() == 18`, `displayName() == "Nota Twin"`, `setSampleRate`, a silent `render()`, `clone()` (copies `pn_`, sample rate, pattern snapshot), `activeVoiceCount`, `heldNotes`, sleep contract stubs+- [X] T008 Implement `getState` / `setState` in `src/devices/instruments/Twin.cpp` with the layout `[u32 magic "TWN1"] [u32 paramCount] [paramCount × f32 LE] [u32 patternBytes] [pattern data]`; `setState` MUST tolerate a shorter / longer param array and a missing pattern block (FR-052)+- [X] T009 Register kind 18 natively, mirroring Consort: `src/engine/Engine.h` (`addTwinTrack` decl), `src/engine/Engine_Devices.cpp` (method, include, `cloneInstrument` and `makeBuiltinInstrument` switches), `src/devices/DeviceFactory.cpp`, `src/devices/racks/RackCore.{h,cpp}` (`makeInstrument`) — done; `cloneInstrumentBody` needs no case (Twin::clone covers it)+- [X] T010 Add `nota_engine_add_twin_track` to `include/nota/nota_engine.h` (comment per contracts/c-abi.md, next to the Consort decl) and implement it in `src/abi/nota_engine_track.cpp`+- [X] T011 [P] Managed interop: `Nota.Infrastructure/Interop/NativeMethods.Tracks.cs` (`[LibraryImport]`), `Nota.Infrastructure/Interop/NotaEngine.Tracks.cs` (`AddTwinTrack`), `Nota.Application/Engine/IAudioEngine.cs`+- [X] T012 [P] Catalog and categories: `Nota.Application/Palette/BuiltinDeviceCatalog.cs` (name "Nota Twin", `Kind = 18`, sub text, semantic descriptor — role, aliases incl. "polysynth", "morph", "analog poly", character, sound, genre, one-line description; the `--palette` smoke check fails without role + aliases) and `Nota.Application/Palette/DeviceCategories.cs`+- [X] T013 [P] Remaining kind sites, mirroring Consort in each: `Nota.Infrastructure/Persistence/ProjectService.cs`, `Nota.Infrastructure/Persistence/PresetService.cs` (add-track switch), `Nota.Infrastructure/Audition/PresetAudition.cs`, `Nota.Presentation/DeviceInsertService.cs`, `Nota.Presentation/Racks/RackKeyParams.cs`, `Nota.App/DeviceCards/Rack/RackCard.Chains.cs`, `Nota.App/DeviceCards/Rack/RackCardView.cs`, `Nota.App/DeviceCards/Rack/RackCardView.Drum.cs`, `Nota.App/DeviceChainView.Shell.cs`, `Nota.App/NotaDocs.cs`, `Nota.App/PreferencesWindow.cs`, `Nota.App/Theme/NotaGeometry.cs`, `Nota.App/Controls/Knob.cs`, `Nota.Remote/RemoteParams.cs`, `Nota.Mcp/Tools/InstrumentTools.cs` (kind list `(18, "Nota Twin")` and the add switch)+- [X] T014 [P] Perf: add `case 18: return "Twin";` in `tests/perf/nota_perf.cpp` `instrumentName`, so the generic `instrument-18` scenario appears in `nota_perf list`+- [X] T015 Smoke: create `tests/Nota.SmokeTest/TwinTests.cs` and hook it into `tests/Nota.SmokeTest/Program.cs`; first check — `AddTwinTrack` returns a track whose kind is 18, param count ≈ the table size, every param id unique, state round-trips through get/set (contract item 5, params only)+- [X] T016 Measure risk R2a: with a Twin track, open the automation target picker, the browser's Map tab, MIDI-learn list and Nota Remote's param list; record the timing in `specs/055-morph-poly-synth/research.md` (R2a) and, if any list is slow or unusable, add the filter to the current part / side there (task appended to US2) — measured: speed is fine, the lists are unwieldy (≈250 top-level automation entries, 121 Remote pages); fixes appended as T092 / T093 (research R2a)++**Checkpoint**: Twin appears in the browser, adds a track, saves and loads — silently.++---++## Phase 3: User Story 1 — Play a rich analog poly (P1) 🎯 MVP++**Goal**: the 12-voice analog voice from Init sounds and responds smoothly (FR-001 – FR-013).++**Independent Test**: spec US1 — held 8-note chord, sweep Wave / Mode / Route / cutoffs, no+clicks, no dropped voices; 13th note steals cleanly.++### Tests for US1++- [X] T017 [P] [US1] Smoke in `tests/Nota.SmokeTest/TwinTests.cs`: Init note renders non-silent and within ±1.5 dB of Volt Init (US1-1, contract item 1); 13 held notes with 12 voices → 12 sound, no NaN/inf; Unison stacks all voices on one key; max Brute + max resonance on both filters stays below +6 dBFS+- [X] T018 [P] [US1] Perf scenarios `twin-full-12` (sustained 12-note chord, both filters, 3 LFOs, FX on once US5 lands) and `pentad-full-16` in `tests/perf/nota_perf.cpp` — `pentad-full-16`, `twin-full-12` added; Twin 12 voices = 1.55 × Pentad 16 after US1, 1.75 × after US3's expression (SC-001 budget 2 ×, matrix and FX still to come) — T050 must optimise++### Implementation for US1++- [X] T019 [P] [US1] `SteinerFilter` in `src/dsp/primitives/SteinerFilter.{h,cpp}`: 12 dB ZDF Sallen-Key-type core, input distributed over LP / BP / HP injection points so `mode` sweeps LP → BP → HP → Notch continuously, diode-pair soft clip in the feedback, self-oscillation at max resonance, per-sample linearised saturation, `NOTA_RT_SAFE`, inline hot path (research R5) — header-only primitive+- [X] T020 [P] [US1] Oscillator in `src/devices/instruments/TwinVoice.{h,cpp}` on the `pentad::` polyBLEP / polyBLAMP core: continuous `wave` tri → saw → square with `pw`, `metal` wavefolder on the triangle path with first-order ADAA, `coarse` ±24 st, `fine`; Osc 2 `o2lo` low-frequency / keyboard-off; hard `sync` 2 → 1, `fm21`, `fmfilt` (osc → multimode cutoff) — all inside the voice's ×2 oversampling with HIIR decimation (research R4)+- [X] T021 [US1] Voice in `src/devices/instruments/TwinVoice.{h,cpp}`: noise with colour, mixer with per-source level and filter balance (`oNbal`, `noisebal`), multimode + ladder (`ldslope` 12/24 via T004), `route` series ↔ parallel blend, `brute` feedback through one-sample delay + tanh with loop gain ≤ 1, `drive`, filter / amp / mod envelopes (mod env with delay + loop), key tracking and env amounts, control-rate (32-sample) coefficient updates, per-sample smoothing of targets — the shared ladder runs one internal step at the voice's ×2 (`setInternalOversampling`), its resonance follows the measured self-oscillation edge per coefficient so full resonance sings at any pitch (no other instrument uses it)+- [X] T022 [US1] LFOs in `src/devices/instruments/TwinMod.{h,cpp}`: 3 LFOs — shapes sine / triangle / saw / square / S&H / smooth random, rate free or synced (`setTransport`, AR-9), per-voice or global mode, retrigger, fade-in; LFO 3 symmetry / curve; hard-wired `vibamt` (LFO 1 → pitch, scaled by mod wheel) and `velamp`+- [X] T023 [US1] Voice pool and render in `src/devices/instruments/Twin.cpp`: 12-voice pool (cap `voices` 4..12), Poly / Mono / Legato / Unison, glide (+ legato-only), quietest / oldest stealing with a short fade (no click), Unison detune + `spread` / `spreadmode`, part `vol` / `pan`, seeded `drift` per voice (Pentad's scheme, re-seed on play edges / jumps), voices released (not cut) when `voices` drops; Lower part only in this slice+- [X] T024 [US1] Sleep contract in `src/devices/instruments/Twin.cpp`: `hasTail` / `isIdle` / `wake` — idle only when every voice envelope is done (FX tails added in US5), phases advance across a skipped block (SC-006)+- [X] T025 [US1] First card `Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs` + `Nota.App/DeviceCards/InstrumentCardFactory.cs`: L size, tabs Osc · Filter · Env · LFO built from the shared gauge knob and Volt's signal-chain panel layout (`nota-instrument` § 3, `nota-design`); knobs bound to `lo.a.*` until US2 adds the side switch — 700 × 260 (DESIGN.md card format): Morph column on every tab + tabs Osc · Filter · Env · LFO · Voice; checked headless in Studio Dark / Light+- [X] T026 [US1] Starter presets in `Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs`: ~12 `Inst("twin", 18, …)` presets (pads, keys, brass, bass, lead) — single-side for now, revisited in US2 / US6 — 12 single-sided patches (Pads, Keys, Brass, Bass, Leads, Plucks, FX); smoke: ids exist, apply in place, 8-note chord at velocity 100 peaks under 0 dBFS++**Checkpoint**: Twin plays as a fine single-sided poly.++---++## Phase 4: User Story 2 — Morph between two sides of a patch (P1)++**Goal**: every param has A and B; Morph interpolates them (FR-020 – FR-024).++**Independent Test**: spec US2 — A dark pad, B bright pluck, automate Morph over 4 bars;+Morph 0 / 1 equal A / B alone.++### Tests for US2++- [X] T027 [P] [US2] Smoke in `tests/Nota.SmokeTest/TwinTests.cs`: render with Morph = 0 equals the render of the same patch with B copied from A, bit-exact (seeded drift); same for Morph = 1 vs A copied from B (SC-002, contract item 2); a Morph 0 → 1 sweep over one beat has no sample-to-sample jump above the A/B renders' own maximum (SC-003) — Morph 1 = side B alone and equal sides at Morph 0.5 = Morph 0, both bit-exact; a one-beat sweep's largest sample step stays within 1.25 × the sides' own++### Implementation for US2++- [X] T028 [US2] Morph evaluation in `src/devices/instruments/TwinMod.{h,cpp}`: at control rate per part, `v = lerp(A, B, morph)` per continuous param **in its musical domain** (pitch-linear for cutoffs / tune, log-time for envelope / LFO times, linear for levels and depths); stepped params "A below 0.5, B from 0.5"; exact endpoints (`lerp(A,B,0) == A`); voice-mode switch at the midpoint releases rather than cuts held notes (research R3) — in `TwinMod.cpp` `evalPart`; the normalized value of a Pitch / LogTime param is already exponential in its unit, so lerping it moves cutoffs in pitch and times logarithmically. Voice mode, glide and octave are side-less part params, so they never switch mid-morph+- [X] T029 [US2] Per-voice morph hook in `src/devices/instruments/TwinMod.cpp` + `TwinVoice.cpp`: each voice holds its own morph value (part morph + per-voice matrix contribution, clamped 0..1) and re-evaluates only voice-local params when it differs from the part's (the matrix source arrives in US4; the hook is tested here with a fixed offset) — `Voice::morphOff` / `own`: a voice with an offset evaluates its own PartCtl; nothing sets the offset until the matrix routes a per-note source to Morph, so its test lands with US4 (T039)+- [X] T030 [US2] Card A/B editing in `Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs` and `Nota.App/Controls/TwinViews.cs`: A / B side switch (view state, not saved in presets), knobs re-bind to `<part>.<side>.*`, each knob shows both side values and the live morphed position (scope index 6), Morph control in the header strip; follows `DESIGN.md` (orange only for what is live / chosen) — A / B "Edit" switch under Morph (editor state per track), every side knob ticks the other side and dots the sounding value (new `Knob.OtherValue` / `SoundingValue`), tooltip "A … · B … · now …"; status shows the edited side+- [X] T031 [US2] Copy A → B, B → A, swap in `Nota.Application/Twin/TwinSides.cs` (pure logic: list of `(id, value)` writes from the param table) and wire to the card's side menu as **one mix gesture** in the engine undo history (research R14) — `Nota.Application/Twin/TwinSides.cs`; a mix gesture takes ≤ 64 targets (`nota_mix_gesture_begin`), so the writes run in 64-target gestures inside one undo group — still one undo step (smoke-tested)+- [X] T032 [US2] Automation lanes name their side: verify Twin's display names (T007, `src/native/nota.engine/src/devices/instruments/Twin.cpp`) reach the automation lane header and target picker in `src/managed/Nota.App/` as "Lower A · Ladder Cutoff" / "Lower B · …"; add the part/side filter if T016 found the lists slow (FR-024) — with T092: the automation menu shows Lower A › Ladder › Cutoff (13 top-level entries, built in 14 ms; checked headless)+- [X] T092 [US2] Automation menu nesting in `Nota.App/ArrangementView.Automation.cs` `BuildBuiltinInstrumentAutoMenu`: a name with " · " nests on that first (`Lower A` › `Ladder` › `Cutoff`), then the existing last-space grouping; rename Twin's matrix params in `src/native/nota.engine/src/devices/instruments/Twin.cpp` so a part / side's 64 slots form one "Routing" group ("Lower · Routing Source1", "Lower A · Routing Depth1") — research R2a — done; global names made single-leaf ("Patch SplitKey")+- [X] T093 [US2] Nota Remote in `Nota.Remote/RemoteParams.cs` `MacroDevices`: for kind 18 page a curated list (Lower Morph, pad X / Y / Z, the Lower part's side-A Osc / Filter / Env controls) instead of all 965 params — research R2a — 28 curated params (4 pages) for kind 18+- [X] T033 [US2] Make the starter presets two-sided in `Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs` (each preset's B side a meaningful variation) — `Tw(name, a, b)`: side B = A + overrides (presets reset unlisted params, so B used to be Init); smoke: both sides sound, peak < 0 dBFS, B ≠ A for all 12++**Checkpoint**: P1's defining feature works; automation writes to the edited side.++---++## Phase 5: User Story 3 — Play it expressively (P1)++**Goal**: velocity, AT, poly AT, MPE, wheels, pedal, expression pad (FR-030, FR-031, FR-033).++**Independent Test**: spec US3 — poly AT / MPE on one note of a chord changes only that note;+recorded expression plays back the same.++### Tests for US3++- [X] T034 [P] [US3] Smoke in `tests/Nota.SmokeTest/TwinTests.cs`: per-note pressure on one note of a held 6-note chord leaves the other five notes' render within 0.5 dB (render each note isolated by pitch through a narrow band or by rendering with/without the pressure event) (SC-005, contract item 3); per-note bend moves only its voice; channel pressure moves all — pressure on one note of a 6-note chord: others within 0.04 dB, its 3rd harmonic +14.7 dB; +2 st per-note bend moves only G3; channel pressure opens 6/6; pad X / Y audible. Recording keeps per-note expression through the engine's existing MPE recording (no Twin-specific path)++### Implementation for US3++- [X] T035 [US3] `noteExpression` / `supportsMpe` / `controller` in `src/devices/instruments/Twin.cpp`: per-voice bend (own range from the MPE controller, else `bendrange` ±2/±5/±12/±24), pressure (poly AT per note; channel AT → all voices), slide, release velocity; mod wheel, pitch wheel, sustain via the engine's default pedal handling (`handlesSustain() == false`) — per-voice `VoiceExpr` + instrument-wide `GlobalExpr` offsets (bend range ±2/5/12/24 from `bendrange`); release velocity isn't delivered by the engine's noteOff, so it waits for an engine change (not in this feature)+- [X] T036 [US3] Default expression routes on Init in `src/devices/instruments/TwinMod.cpp`: mod wheel → vibrato (via `vibamt`), pressure → ladder + multimode cutoff, slide → multimode cutoff, velocity → amp — implemented as fixed routes now, re-expressed as removable matrix slots in US4 (FR-033) — fixed routes until US4 re-expresses them as removable slots: pressure → both cutoffs +1.5 oct, slide → multimode ±2 oct, mod wheel → vibrato (+ pad Z)+- [X] T037 [US3] Expression pad in `Nota.App/Controls/TwinViews.cs` + the card: X / Y drag, Z = hold time / press (mouse) or touch pressure, writing `padx` / `pady` / `padz` (automatable); default routes X → multimode cutoff, Y → morph, Z → LFO 1 depth until US4 makes them editable — `TwinExpressionPad` (Controls/TwinViews.cs) on the Voice tab: drag X / Y, hold raises Z over 0.5 s, release lets it fall over 0.25 s; one automation-write gesture on the three axes; X → multimode cutoff ±2 oct, Y → morph ±½, Z → vibrato depth+- [X] T038 [US3] MPE badge and Nota Remote Expressive keys: confirm `supportsMpe()` shows the badge and that `Nota.Remote/RemoteParams.cs` exposes the pad and Morph on the phone — `supportsMpe()` = true drives the MPE badge; Morph and pad X / Y / Z lead Nota Remote's curated pages (T093)++**Checkpoint — end of slice P1**: run Phase 12's closing tasks for PR 1 (build, smoke, CHANGELOG, FEATURES, docs) and open PR 1.++---++## Phase 6: User Story 4 — Route modulation in a matrix (P2)++**Goal**: 64-slot matrix per part, 8 macros (FR-032 – FR-034).++**Independent Test**: spec US4 — LFO 3 → Osc 1 Wave and → multimode cutoff with opposite+depths; delete one route; fill 64 slots → "matrix full".++### Tests for US4++- [X] T039 [P] [US4] Smoke in `tests/Nota.SmokeTest/TwinTests.cs`: a route with depth 0 renders identically to no route; LFO → cutoff route with A depth ≠ B depth changes with Morph; a per-note source → `morph` route morphs only its note — plus: the app's tables match the engine (29 sources, 77 destinations), first-free-slot add + one-step undo, full at 64, remove frees the slot; zero depth renders bit-identically to no route; a B-only depth moves only at Morph 1; Pressure → Morph morphs only the pressed note (closes T029's test)++### Implementation for US4++- [X] T040 [US4] Source and destination tables in `src/devices/instruments/TwinMod.h` — **append-only enums**: sources none, LFO 1–3, filter env, amp env, mod env, velocity, release velocity, key, pressure, slide, per-note bend, mod wheel, pitch wheel, pad X / Y / Z, random-per-note, macro 1–8, seq gate, seq step value; destinations = every continuous voice / part param + `morph`; stepped params are not destinations (data-model § Validation) — `TwinMod.h` / `.cpp`: 29 sources, 6 virtual destinations (Morph, Pitch, Osc 1 / 2 pitch, Vibrato) + 71 side params; slot texts read as names (`pluginParamText`)+- [X] T041 [US4] Matrix evaluation in `src/devices/instruments/TwinMod.cpp`: 64 slots per part read from `mN.src` / `mN.dst` and the morphed `mNamt`; per-voice sources evaluate per voice, global ones once per control block; destination offsets summed in each param's musical domain; a slot with `src = none` or `dst = none` is empty — per voice at control rate: a route moving anything makes the voice evaluate its own PartCtl with the offsets (normalized side offsets, morph, pitch ±24 st, vibrato ±1 st); LFO 2 / 3 step once per interval; 16 live routes cost ≈ 4 ms/s (twin-full-12: 1.75 × Pentad 16)+- [X] T042 [US4] Move the Init defaults of T036 / T037 into matrix slots 1–7 (removable), keeping old projects' sound: on `setState` of a pre-matrix blob, write the equivalent slots — slots 1–6 are the Init routes (pressure → both cutoffs, slide and pad X → multimode, pad Y → morph, pad Z → vibrato) as param defaults; the fixed code paths are gone. No migration: nothing has shipped+- [X] T043 [US4] Macros in `src/devices/instruments/TwinMod.cpp`: 8 `macroN` values per part as matrix sources plus Volt-style macro → several destinations, as on Volt / Aurora — macros are the part's eight `macroN` params, matrix sources (one macro → many destinations through routes); eight knobs on the Matrix tab+- [X] T044 [US4] Matrix tab in `Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs` + `Nota.App/Controls/TwinViews.cs`: source × destination grid; click creates a route in the next free slot, drag sets bipolar depth on the edited side, delete removes; each a single undo step; "Matrix full (64 routes)" message when no slot is free (FR-032 acceptance 2) — a route list rather than the spec's grid (29 × 77 does not read in 186 px): slot, source ▾, destination ▾ (grouped menus), depth on the edited side (other side ticked), remove; "+ Route", "n / 64", "Matrix full (64 routes)"; each edit one undo step (`Nota.Application/Twin/TwinMatrix.cs`). The open tab survives the A / B rebuild+- [X] T045 [US4] MCP `set_twin_route` and `read_twin` (routes part) in `Nota.Mcp/Tools/TwinTools.cs` per contracts/mcp-tools.md (`next_free`, "matrix full" error), registered next to `InstrumentTools` — `read_twin` (sides of 22 main controls, routes by name) and `set_twin_route` (by name, slot or first free, remove, "matrix full"); smoke-tested++**Checkpoint**: deep modulation per side.++---++## Phase 7: User Story 5 — Finish the sound with its own effects (P2)++**Goal**: Mod FX / Delay / Reverb per part, morphable, bypassable (FR-040).++**Independent Test**: spec US5 — each effect on/off, full bypass, morph dry A → long-reverb B.++### Tests for US5++- [X] T046 [P] [US5] Smoke in `tests/Nota.SmokeTest/TwinTests.cs`: `fxon = 0` render equals the voice sum alone; synced delay follows a tempo change; after note-off the instrument stays awake until the tail is below the silence threshold — plus: every effect (chorus, flanger, phaser, ensemble, delay, reverb) heard, finite, under 0 dBFS; the synced 1/4 echo lands 0.500 s after the note at 120 BPM and 0.667 s at 90; a reverb tail is at −28 dB 0.75 s after the note++### Implementation for US5++- [X] T047 [US5] Internal FX chain in `src/devices/instruments/Twin.{h,cpp}`: per part, construct once a Chorus, Flanger, Phaser (one active by `modfxtype`), Delay and Reverb from `src/devices/effects/` (no allocation after construction), forward `setSampleRate`, `setTransport` / `TransportInfo` for delay sync; per block push the morphed `modfx*` / `dly*` / `rev*` values onto the devices' params (research R8) — devices built in the constructor and re-rated in `Twin::setSampleRate` (the engine changes rates with rendering suspended; Delay / Reverb size their lines there); per part: decimate → Mod FX ▸ Delay ▸ Reverb at the instrument's output gain; an effect switched on starts from a cleared line; resets clear them for repeatable renders. Patch-wide sources (wheels, pad, macros, global LFOs) now act on the part's values — so they reach the effects — and a voice re-evaluates only for its own sources. Delay Division follows the device's 8 values+- [X] T048 [US5] Extend the sleep contract (T024) with the FX tails: delay flight time and reverb tail block sleep (Consort's rule) (US5-3) — the output-peak hangover already covers the tails (the tail is output); smoke-tested+- [X] T049 [US5] FX tab in `Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs`: three effect panels with on/off, mix, two or three character knobs, the whole-section bypass — FX tab: Mod FX (Chorus / Flanger / Phaser / Ensemble, rate, depth, mix), Delay (sync / ping-pong, time or division, feedback, mix), Reverb (size, damping, mix), each with On, and the section switch; checked headless in both themes+- [X] T050 [US5] Add `twin-full-12` with FX on and confirm SC-001 (≤ 2 × `pentad-full-16`) in `tests/perf/nota_perf.cpp`; if over budget, apply research's mitigations (control-rate coefficients, SIMD across voices via `src/dsp/math/Simd.h`, SVF fallback for R5) and re-measure — 81.5 ms/s vs Pentad 42 (1.94 ×) with FX on; profiled (`sample`): voice path ≈ 50 %, ladder ≈ 14 %, oscillators ≈ 15 %, reverb ≈ 5 %. Steiner ZDF coefficients now refresh with the cutoff instead of every os sample and expMap uses the fast exp2: 78.4 vs 42.6 = 1.84 × (SC-001 met, ~8 % margin)++---++## Phase 8: User Story 6 — Start from presets (P2)++**Goal**: ≥ 40 factory presets in folders, user presets, preset name / "modified" (FR-053).++**Independent Test**: spec US6 / SC-004 — every preset sounds on both sides, peaks under+0 dBFS with an 8-note chord at velocity 100, loads under 50 ms.++### Tests for US6++- [X] T051 [P] [US6] Smoke in `tests/Nota.SmokeTest/TwinTests.cs`: loop over every `twin` factory preset — non-silent at Morph 0 and 1, peak < 0 dBFS (8-note C-major chord, velocity 100), apply time < 50 ms; save a user preset and re-apply it → identical render; the "modified" mark (specs/048) appears after one knob move and clears on undo — 43 presets in 10 folders; both sides sound, peak < 0 dBFS, B ≠ A for all; apply ≤ 1.5 ms (was 40.7 ms: `Engine::instrumentParamDefault` built a fresh instrument per question — now one per kind, cached); the preset name and "modified" mark follow a side-B knob; a user preset round-trips all 964 sound params++### Implementation for US6++- [X] T052 [US6] User presets in `Nota.Infrastructure/Persistence/PresetService.cs`: Twin saves `NamedParams` (skip view params) and, from P3 on, the pattern block in `StateBase64`; apply params first, then the blob (research R11) — the generic built-in path already captures every named param (sides, matrix, FX); the pattern block joins with US8+- [X] T053 [US6] Factory library in `Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs`: ≥ 40 presets in folders Pads, Keys, Leads, Bass, Brass, Strings, Plucks, Sequence, FX, Morph — each with a meaningful B side and macro names; no Arturia names — 43 two-sided presets (Pads, Keys, Brass, Bass, Leads, Plucks, Strings, Sequences, FX, Morph), many with matrix routes (`Rt` helper) and effects; macros carry no names yet (Twin has no macro-name storage) — the presets route the sound directly instead. "Morph" joins the preset descriptors' folder map+- [X] T054 [US6] Preset audition: confirm `Nota.Infrastructure/Audition/PresetAudition.cs` plays Twin presets with a held chord long enough to hear the morph (adjust the audition phrase for kind 18 if needed) — the audition picks its phrase from the folder; "morph" now plays the held-chord (Pad) phrase so an LFO-driven morph can travel++---++## Phase 9: User Story 7 — See and edit it on a device card (P2)++**Goal**: the full card — L and S sizes, graphs, every tab, all themes.++**Independent Test**: spec US7 — edit a full patch from the card; S ↔ L; A/B indicator, live+morph and per-knob markers in all four themes.++- [X] T055 [P] [US7] Interactive graphs in `Nota.App/Controls/TwinViews.cs`: per-oscillator waveform (draws Wave / PW / Metal, drag = wave), combined dual-filter response with route blend (drag = cutoffs / resonance), envelope shapes (drag points), LFO shapes with live phase (scope 20–22) — `Controls/TwinViews.cs`: oscillator waveforms in the Osc headers (drag = Wave), the two filters' combined response with the multimode and ladder faint (drag = ladder cutoff / resonance), envelope graphs with A · D/S · R handles (the env islands keep Velocity and Curve as knobs, times read out under the graph), LFO shapes with the live phase+- [X] T056 [US7] S size in `Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs`: Morph, A/B switch, expression pad and the key sound knobs (cutoffs, resonance, attack, release); size saved with the project as a view param — 260 wide: Morph + A / B, the pad, ladder cutoff / resonance and amp attack / release of the edited side; the S / L toggle in the header; `view` now defaults to L+- [X] T057 [US7] Voice meter and live morph markers in `Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs`: read `activeVoiceCount` and scope 4–19 at the card's refresh rate; per-voice morph dots on the Morph control — the header's voice count (n / cap); a live morph strip under the Morph knob (the part's morph and a dot per sounding voice) from the new `scopeRead` telemetry (contracts/c-abi.md layout)+- [X] T058 [US7] Design check in `tests/Nota.SmokeTest/` design-token suites (`DesignTokenCheck*.cs` allow lists): Twin card labels sentence-case, tokens only, no ad-hoc colours; screenshots of S and L in Studio Dark, Studio Light, Ember Graphite, Ember Paper via the in-app capture recipe for the PR — the full smoke (design token, label, icon and card-format checks) passes; headless shots of every tab, side B and S in Studio Dark, Studio Light, Ember Graphite and Ember Paper (/tmp/twin-cardharness/out)+- [X] T059 [US7] MCP side tools `set_twin_morph_side`, `copy_twin_side` and full `read_twin` in `Nota.Mcp/Tools/TwinTools.cs` (contracts/mcp-tools.md) — `set_twin_morph_side` ("id=value" list on side a / b) and `copy_twin_side` (a_to_b / b_to_a / swap), one undo step each; smoke-tested++**Checkpoint — end of slice P2**: Phase 12 closing tasks for PR 2; open PR 2.++---++## Phase 10: User Story 8 — Sequence it from the instrument itself (P3)++**Goal**: polyphonic step sequencer, arpeggiator, motion lanes, patterns in presets, "To clip"+(FR-060 – FR-067).++**Independent Test**: spec US8 — step-record 4 chords, play at 90 and 174 BPM, transpose by a+held key, record a Morph motion lane, "To clip", sequencer off — same sound.++### Tests for US8++- [X] T060 [P] [US8] Smoke in `tests/Nota.SmokeTest/TwinTests.cs`: a 16-step pattern started by the transport fires note-ons exactly on the step grid at 90 and 174 BPM over 64 bars (≤ 1 sample deviation) (SC-009, contract item 4); transport stop releases every sequencer note; a loop jump re-aligns with no hanging note; state round-trip keeps patterns (contract item 5, pattern block) — 1/16 steps land on the grid at 90 and 174 BPM (onset spacing within 1 sample over 4 s; the smoke keeps it to 4 s, not 64 bars, to stay quick); a running pattern renders bit-identically at blocks of 512 and 77; a transport stop releases every sequencer note; patterns round-trip through the state+- [X] T061 [P] [US8] Smoke: "To clip" output renders identically to the running pattern with Twin's sequencer off (SC-009 second half) — "To clip" plays like the pattern (level within 0.00 dB, onsets within 2 samples) and its undo restores the sequencer++### Implementation for US8++- [X] T062 [US8] Check how Nota Rhythm's step edits enter the undo history (`src/devices/instruments/RhythmMachine.cpp` `action()` and its callers in `src/managed/`) and record the finding in research.md R14; Twin's pattern edits follow the same path, or add a state checkpoint per action if Rhythm has none — Rhythm\'s step edits were not undoable at all (instrumentAction called action() only). Added a generic path instead: `Instrument::editState / setEditState` + `MixKind::InstrumentEdit`; `Engine::instrumentAction` records an undo step whenever the edit state changes, undo hands the bytes back without republishing (sounding notes go on). Rhythm can opt in later+- [X] T063 [US8] Pattern storage in `src/devices/instruments/TwinSeq.{h,cpp}`: 8 patterns; per pattern `length` "1..64 steps", per step "0..6 MIDI notes (0 = rest)", "velocity 1..127", "gate 1..100 % of step, or tie"; 4 motion lanes with "target param index or none", "stepped / smooth", "value 0..1 or unset" (data-model § Pattern); message-thread authoring copy + immutable `std::shared_ptr` snapshot published by atomic exchange, retired snapshots freed on the message thread (AR-5) — `TwinSeq.{h,cpp}`: patterns, lanes, serialization; `SnapshotHistory<PatternSet>` publishes the immutable snapshot (AR-5)+- [X] T064 [US8] `action()` ids 0–15 in `src/devices/instruments/Twin.cpp` exactly as contracts/c-abi.md (append-only), each bumping the revision (scope 3) and publishing a snapshot; serialize patterns into the state blob's pattern block (T008) — ids 0–15 as contracted plus 16 `StepRecordPoll`; tie is farg > 1 (a gate of 100 % is 1.0)+- [X] T065 [US8] Sequencer engine in `src/devices/instruments/TwinSeq.cpp`: clock from `setTransport` (AR-9) — steps at exact sample offsets from the beat grid, rate 1/4 … 1/32 incl. triplets, swing, pattern length independent of the bar, stopped when the transport isn't rolling, jump / loop → release + re-align at next step; held-key transpose (root = first note of the pattern) with latch; pending pattern switch applied at pattern end (scope 0–2); played keys sound alongside the pattern — the step grid is absolute (song-start based), whole-sample onsets (block positions are rounded to whole samples so block splits never shift a step); stopped transport = silent sequencer, keys play normally+- [X] T066 [US8] Arpeggiator in `src/devices/instruments/TwinSeq.cpp`: Up, Down, Up/Down, Random, As Played, Chord; 1–4 octaves; synced rate, gate, swing, Hold — reuse the note-order logic from `src/devices/midi_fx/Arpeggiator.{h,cpp}` (factor a shared helper, no change to Arp's behaviour) (FR-064) — `twin::arpNotes`: Nota Arp\'s idea (the note is a pure function of the absolute step) rather than its code, which is embedded in the device; Up, Down, Up/Down, Random, As played, Chord; 1–4 octaves; Hold+- [X] T067 [US8] Motion lanes in `src/devices/instruments/TwinSeq.cpp` + `TwinMod.cpp`: per step override of the target param's sounding value (stepped / smoothed), acting on the side the param belongs to; motion-record arm captures the touched param's value per step; a hand-moved knob overrides the lane until released (US8-3) — lanes override a side\'s value (or the part\'s Morph) before the morph; while a lane records its playback pauses (that is how "the hand wins"); the card writes the target\'s value at each step it sees pass+- [X] T068 [US8] Sequencer output into the voice path in `src/devices/instruments/Twin.cpp`: sequencer notes enter like keyboard notes (voice allocation, per-note sources, Split / Layer routing via `seq.target` from US9); MIDI effects before Twin see only incoming notes (FR-067) — sequencer voices are flagged, released only by the sequencer; MIDI effects before Twin see only incoming notes+- [X] T069 [US8] Seq tab in `Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs` + `Nota.App/Controls/TwinViews.cs`: step grid (notes per step, velocity / gate lanes, tie / rest), pattern 1–8 selector with pending indicator, step-record arm, motion lanes view and arm, Seq / Arp switch with arp controls; re-reads the pattern blob when the revision changes — Seq tab: Sequencer on, Seq / Arp, pattern, length, rate, swing, transpose / latch, Rec, To clip; the step grid (notes, velocity drag, gate drag / tie, playing step, record cursor, selection, motion values); Rest, pages, lane 1–4, target, Smooth, Rec motion, Clear; Arp page: mode, rate, octaves, hold, gate, swing+- [X] T070 [US8] "To clip" in `Nota.Application/Twin/TwinPatternToClip.cs`: decode the active pattern from the state blob, create a MIDI clip with its notes and velocities and motion lanes as automation on the lane's param, switch `seq.on` off — one undo step (research R13); wire to the Seq tab — `TwinPatterns.ToClip` (ties merge, swing kept, motion lanes → automation, the sequencer off) in one undo step; the card places the clip at the playhead\'s bar+- [X] T071 [US8] Patterns in presets: `TwinSeq(...)` compact text builder in `Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs` producing the pattern block; ≥ 8 factory presets using sequencer or arp (SC-011); user presets carry patterns (T052) — user presets carry a params-free state blob with the patterns; `TwSeq` builds 8 factory sequencer / arp presets (one with a Morph motion lane)+- [X] T072 [US8] MCP `get_twin_pattern`, `set_twin_pattern`, `twin_pattern_to_clip` in `Nota.Mcp/Tools/TwinTools.cs` (text rows `C3 E3 G3:100:50%`, `.` rest, `~` tie; one undo step per call) — `get_twin_pattern`, `set_twin_pattern` (rows; one undo step; turns the sequencer on), `twin_pattern_to_clip`+- [X] T073 [US8] Sleep: a running sequencer blocks sleep; a stopped one doesn't (SC-006) — a running sequencer keeps the instrument awake (the 4-second grid test would lose onsets otherwise)++---++## Phase 11: User Story 9 — Split or layer two sounds (P3)++**Goal**: Lower / Upper parts, Single / Layer / Split, shared 12 voices (FR-070 – FR-075).++**Independent Test**: spec US9 — Split at C3 with two presets in Lower / Upper; share 4 + 8;+6 keys held low → 4 sound.++### Tests for US9++- [X] T074 [P] [US9] Smoke in `tests/Nota.SmokeTest/TwinTests.cs`: Split at C3 — B2 renders only Lower, C3 only Upper; share 4 + 8 with 6 low keys → 4 Lower voices, Upper keeps 8; Layer plays both parts per key; mode change with held notes leaves no hanging note+- [X] T075 [P] [US9] Perf scenario `twin-layer-6x6` in `tests/perf/nota_perf.cpp` within SC-001's budget (SC-010)++### Implementation for US9++- [X] T076 [US9] Parts in `src/devices/instruments/Twin.cpp`: run the Upper part's morph / matrix / FX / voices (already in the param table, T006); `mode` Single / Layer / Split; `splitkey` "MIDI 0..127" (first key of Upper); `share` "Lower 2..10 (step 2)", "Upper = 12 − Lower", "Single → all 12 to Lower"; per-part allocator over its slice, stealing only within the part; share / mode changes release surplus voices (research R12)+- [X] T077 [US9] Per-part `octave` transpose (Split), `vol` / `pan` balance (Layer), per-part voice mode and glide; performance controls and expression reach both parts; `seq.target` Lower / Upper / Both (FR-072, FR-074)+- [X] T078 [US9] Card part switch in `Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs`: Lower / Upper switch next to A / B (shown in Layer / Split), mode selector, split-key control (click "learn" from a played key), share slider; param names carry the part (FR-073)+- [X] T079 [US9] Copy part and load preset into part in `Nota.Application/Twin/TwinParts.cs`: remap `lo.*` ↔ `up.*` ids; "Load into Lower / Upper" from the preset picker; loading into Upper of a Single patch turns it to Layer with the current sound as Lower; one undo step each (FR-075, US9-4)+- [X] T080 [US9] ≥ 6 Split / Layer factory presets in `Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs` (SC-011); `read_twin` reports mode / split / share (`Nota.Mcp/Tools/TwinTools.cs`)++**Checkpoint — end of slice P3**: Phase 12 closing tasks for PR 3; open PR 3.++---++## Phase 12: Polish & Cross-Cutting (run per slice PR)++- [X] T081 Run quickstart.md sections 1–4 for the slice and record results in the PR description+- [X] T082 [P] Determinism: render the same project twice and after save / load — identical output (SC-008), including drift and sequencer+- [X] T083 [P] Edge cases from spec § Edge Cases not already covered: sample-rate change, offline render at another rate, clone / copy-paste / freeze / Instrument Rack chain of a Twin (both sides, matrix, FX, patterns come along)+- [X] T084 SC-007 walkthrough: build a two-sided morphing pad from Init in < 5 min using only the card; write it as the docs walkthrough (feeds T089)++### Nota closing tasks *(PR gates — per slice)*++- [X] T085 Run `scripts/build.sh` (or `scripts/build-linux.sh` / `scripts/build-win.ps1`) until native + managed + smoke test are green+- [X] T086 AGPL-3.0-only SPDX two-line header on every new source file (`Twin*.{h,cpp}`, `SteinerFilter.{h,cpp}`, `TwinInstrumentCard.cs`, `TwinViews.cs`, `TwinTools.cs`, `Nota.Application/Twin/*.cs`, `TwinTests.cs`)+- [X] T087 New dependency: N/A (none added; HIIR already listed in `LICENSES/third-party.md`)+- [X] T088 `CHANGELOG.md` `[Unreleased]` entry for the slice (Added: Nota Twin …)+- [X] T089 FEATURES.md via the `nota-features` skill; user docs EN + RU via `nota-docs` (new instrument page, screenshots); shortcuts via `nota-shortcuts` if the card adds any (else N/A)+- [X] T090 Smoke coverage confirmed for every engine behaviour the slice changed (`tests/Nota.SmokeTest/TwinTests.cs`)+- [X] T091 `/speckit-converge` reports Converged for the slice's stories before the PR (constitution quality gate)++---++## Dependencies & Execution Order++### Phase dependencies++- **Setup (1)** → **Foundational (2)** → stories. T004–T005 (slice 0) can merge on their own+ before anything else; T021 needs T004.+- **P1**: US1 → US2 → US3 (US2 morphs US1's params; US3's pressure → morph needs US2's per-voice hook).+- **P2**: US4 needs US2 (per-side depths) and US3 (expression sources). US5 needs US1 only.+ US6 needs US2 + US4 + US5 (presets use them). US7 needs US4 + US5 (its tabs).+- **P3**: US8 needs US4 (seq sources), US6's preset blob path (T052). US9 needs US8's+ `seq.target` only for T077; otherwise independent of US8.+- **Polish (12)** closes each slice.++### Story dependency graph++```text+Setup → Foundational ─┬─ US1 → US2 → US3 ──(PR 1)+ │ │ │+ │ └──┬───┘+ │ US4 ─┐+ ├─ (US1) → US5 ───┼─ US6 → US7 ──(PR 2)+ │ │+ │ US8 ─────────────┐+ └─ (US4) ────────────────── US9 ──┴─(PR 3)+```++### Within each story++Tests first (they should fail), then engine DSP → engine wiring → managed → card → presets / MCP.++### Parallel opportunities++- Foundational: T011, T012, T013, T014 touch different files — parallel after T010.+- US1: T019 (filter) ∥ T020 (oscillator) ∥ T017 / T018 (tests); T021 joins them.+- US5 ∥ US4 once P1 is merged (different files: FX in `Twin.cpp` sections vs `TwinMod.*` — coordinate on `Twin.cpp`).+- US8 ∥ US9 engine work (`TwinSeq.*` vs part logic in `Twin.cpp`) — US9's T077 waits for T068.+- Tests marked [P] in each story are independent of each other.++## Parallel Example: User Story 1++```bash+Task: "SteinerFilter in src/native/nota.engine/src/dsp/primitives/SteinerFilter.{h,cpp}" # T019+Task: "Oscillator in src/native/nota.engine/src/devices/instruments/TwinVoice.{h,cpp}" # T020+Task: "Smoke Init / steal / unison / bounded-level checks in tests/Nota.SmokeTest/TwinTests.cs" # T017+Task: "Perf scenarios twin-full-12 and pentad-full-16 in tests/perf/nota_perf.cpp" # T018+```++## Implementation Strategy++### MVP first++1. Phase 1 + 2 (with slice 0 merged as its own PR).+2. US1 → **validate**: a good single-sided poly.+3. US2 + US3 → **PR 1**: the MVP is the *morphing, expressive* poly — US1 alone would ship "another+ two-oscillator poly", which the spec explicitly calls insufficient.++### Incremental delivery++- PR 1 (P1): US1–US3. PR 2 (P2): US4–US7. PR 3 (P3): US8–US9.+- Each PR keeps the param layout append-only, so projects from an earlier PR open unchanged.++## Notes++- 93 tasks (T092 / T093 appended after the R2a measurement); [P] = different files, no unfinished dependency.+- Commits in the repo's style — the user reviews and commits; do not push.+- Stop at each checkpoint to validate the story on its own.++## Phase 13: Convergence++- [X] T094 Deliver release velocity to Twin: the matrix source "Release velocity" reads 0 (`Twin.cpp` "not delivered yet") because `Instrument::noteOff` carries no velocity; pass note-off velocity through the engine's note-off path (clips, live MIDI, MPE) into Twin and add a smoke check that a route from it moves a release-stage param, per FR-030 (partial)+- [X] T095 Strengthen the sequencer timing proof in `tests/Nota.SmokeTest/TwinTests.cs`: step onsets over 64 bars at 60, 120 and 200 BPM within one sample of the grid, and "To clip" rendering identically to the running pattern (today: 4 s at 90 / 174 BPM, clip compared by onsets ±2 samples and level ±0.5 dB), per SC-009 (partial)+- [X] T096 "Load into Lower / Upper" (`TwinInstrumentCard.cs` **Parts** menu) lists only factory presets: add the user's Twin presets (PresetService.List of kind 18) so two saved sounds can be combined, per FR-075 (partial)+- [X] T097 Motion-lane targets in the card's Seq tab cover Morph and the side params but not the expression pad: add Pad X / Y / Z to the lane target list (the engine already accepts any param index), per FR-063 (partial)+- [X] T098 Add a smoke check that an idle Twin (no notes, effect tails gone) reports idle and costs no render time, with and without a stopped sequencer, per SC-006 (partial)+- [X] T099 Review and justify in the PR the engine additions beyond the plan: `Delay::A_Reset` / `Reverb::A_Reset` (fresh-device reset for Twin's silent-start re-seed, SC-008) and `nota_audition_instrument_state` (preset audition plays a Twin preset's pattern); record them in `contracts/c-abi.md`, per plan: C ABI contract (unrequested)++## Phase 14: Hand test of PR #406 (2026-11-06)++- [X] T100 Matrix tab as a grid, as Nota Consort's patch matrix (`TwinPatchMatrix` in `Nota.App/Controls/TwinViews.cs`, the card's Matrix tab): sources × destinations, drag a cell for the edited side's depth (a new route is the same on both sides for that drag), double-click / Clear removes, ⌥-click types; rows and columns from the routes first (6 × 5, up to 8 × 6), then the last picked per track and part; the route list goes, per US4 / FR-032+- [X] T101 Seq and Arp from a held key with the transport stopped (`Twin::freeStart` / `freeStop`, `clockAt`): the free clock runs at the host tempo from the key, the last key up stops it, Latch / Hold keeps it; the transport starting hands over to the song grid; the Seq / Arp hint says what to do next (On, an empty pattern, a key); smoke check, per FR-061+- [X] T102 60 more factory presets (117 in all): classic pads, keys, brass, basses, leads, plucks and strings, and creative morph, FX, sequence, arpeggio and split / layer ones; the smoke test requires ≥ 110, per FR-053diff --git a/specs/055-morph-poly-synth/validation.md b/specs/055-morph-poly-synth/validation.mdnew file mode 100644index 00000000..07277ad3--- /dev/null+++ b/specs/055-morph-poly-synth/validation.md@@ -0,0 +1,52 @@+# Validation results: Nota Twin (specs/055)++The quickstart run (T081), recorded for the PR description. macOS (Apple Silicon), Release engine.++## 1. Build and smoke++- `scripts/build.sh`: the engine and the app build. The smoke test in that run had 4653 PASS+ and 2 FAIL: the two "overloaded … late blocks" render-pool checks on Synth tracks. That pair+ is unstable on this machine and fails on the base engine too.+- Smoke test run again on its own, after the convergence tasks (T094–T099): **SMOKE TEST+ PASSED** (4653 PASS, 0 FAIL). The same "overloaded" pair failed in one of three runs. The Twin section+ (`--twin`) passes, including:+ - determinism: the same render twice, after save / load, at 96 kHz and back, frozen vs live+ (SC-008);+ - copy / paste and an Instrument Rack chain;+ - Split / Layer;+ - the sequencer and the arpeggiator;+ - the MCP tools;+ - all 57 presets on both sides.++## 2. CPU budget (SC-001, SC-010)++`nota_perf run <scenario> 5`, wall ms per second of audio:++| Scenario | ms/s | vs Pentad |+|---|---|---|+| pentad-full-16 (16-voice chord) | 47.1 | 1.00× |+| twin-full-12 (12 voices, both filters, 16 routes, FX) | 86.5 | 1.84× |+| twin-layer-6x6 (Layer 6 + 6, both parts' FX) | 82.5 | 1.75× |++Both Twin scenarios are within the 2× budget. An earlier, quieter run gave 39.0 / 73.4 / 70.3+(1.88× / 1.80×).++## Beyond the plan++`contracts/c-abi.md` § "Added during implementation" lists these additions and what each one is for:++- note-off release velocity (FR-030);+- `nota_audition_instrument_state` (sequenced presets preview their pattern);+- `Delay::A_Reset` / `Reverb::A_Reset` (fresh-device reset, so renders repeat exactly, SC-008).++## 3–4. In the app++Each US1–US9 scenario is covered by a smoke check that drives the engine directly. Two parts+were not run by hand:++- **US3 hardware pass:** the KeyLab Essential mk3 poly-aftertouch / MPE check is still to do.+- **SC-007 timing:** the 5-minute "morphing pad from Init" walkthrough is written in the user+ docs (`devices/instruments/twin`) but has not been timed by a person.++Card screenshots for every tab, both sizes, the Split / Upper views and four themes are in the+docs (`devices/instruments/twin/*`) and in the card harness.diff --git a/src/managed/Nota.App/ArrangementView.Automation.cs b/src/managed/Nota.App/ArrangementView.Automation.csindex 444287b6..a810e993 100644--- a/src/managed/Nota.App/ArrangementView.Automation.cs+++ b/src/managed/Nota.App/ArrangementView.Automation.cs@@ -756,35 +756,51 @@ public sealed partial class ArrangementView// A built-in instrument's params listed directly, grouped by name section (the part// before the last space, e.g. "Filter 1"); single-word params (Attack, Volume…) sit- // at the top level. Picking one sets a valid PluginParam target (paramId).+ // at the top level. A name with " · " nests on that first — Nota Twin's+ // "Lower A · Ladder Cutoff" reads Lower A › Ladder › Cutoff — so ~900 params stay a+ // short menu. Picking one sets a valid PluginParam target (paramId).private MenuItem BuildBuiltinInstrumentAutoMenu(IAudioEngine e, TrackVM t, HashSet<string> automated){var root = new MenuItem { Header = e.DeviceName(t.Id, -1) };- var groups = new System.Collections.Generic.Dictionary<string, MenuItem>();+ var tops = new System.Collections.Generic.Dictionary<string, MenuItem>();+ var groups = new System.Collections.Generic.Dictionary<(string, string), MenuItem>();int n = e.PluginParamCount(t.Id, -1);+ static (string Top, string Tail) Split(string nm)+ {+ int dot = nm.IndexOf(" · ", StringComparison.Ordinal);+ return dot >= 0 ? (nm[..dot], nm[(dot + 3)..]) : ("", nm);+ }// Group by the name's head ("Res1 Decay" → Res1 › Decay); a head only one param has// stays a plain entry under its full name ("Note Off", not Note › Off).static string Head(string nm) { int sp = nm.LastIndexOf(' '); return sp >= 0 ? nm[..sp] : ""; }- var sizes = new System.Collections.Generic.Dictionary<string, int>();+ var sizes = new System.Collections.Generic.Dictionary<(string, string), int>();for (int i = 0; i < n; i++){- string h = Head(e.PluginParamName(t.Id, -1, i));- sizes[h] = sizes.TryGetValue(h, out var c) ? c + 1 : 1;+ var (top, rest) = Split(e.PluginParamName(t.Id, -1, i));+ var key = (top, Head(rest));+ sizes[key] = sizes.TryGetValue(key, out var c) ? c + 1 : 1;}for (int i = 0; i < n; i++){string id = e.PluginParamId(t.Id, -1, i);string nm = e.PluginParamName(t.Id, -1, i);if (id.Length == 0 || InstrumentView.IsViewParam(id)) continue; // the card size isn't sound- string grp = Head(nm);- if (grp.Length > 0 && sizes[grp] < 2) grp = "";- string leaf = grp.Length > 0 ? nm[(grp.Length + 1)..] : nm;+ var (top, rest) = Split(nm);+ string grp = Head(rest);+ if (grp.Length > 0 && sizes[(top, grp)] < 2) grp = "";+ string leaf = grp.Length > 0 ? rest[(grp.Length + 1)..] : rest;string pid = id;var item = Leaf(leaf, $"P:-1:{pid}", () => SetAutoPluginTarget(t, -1, pid), automated);- if (grp.Length == 0) root.Items.Add(item);+ MenuItem parent = root;+ if (top.Length > 0)+ {+ if (!tops.TryGetValue(top, out var tm)) { tm = new MenuItem { Header = top }; tops[top] = tm; root.Items.Add(tm); }+ parent = tm;+ }+ if (grp.Length == 0) parent.Items.Add(item);else{- if (!groups.TryGetValue(grp, out var g)) { g = new MenuItem { Header = grp }; groups[grp] = g; root.Items.Add(g); }+ if (!groups.TryGetValue((top, grp), out var g)) { g = new MenuItem { Header = grp }; groups[(top, grp)] = g; parent.Items.Add(g); }g.Items.Add(item);}}diff --git a/src/managed/Nota.App/Controls/Knob.cs b/src/managed/Nota.App/Controls/Knob.csindex 4d2e2616..fc58840e 100644--- a/src/managed/Nota.App/Controls/Knob.cs+++ b/src/managed/Nota.App/Controls/Knob.cs@@ -33,6 +33,7 @@ public sealed class Knob : Controlprivate static readonly IBrush NeutralArc = NotaPalette.Rule; // a knob off the audio path, or disabledprivate static readonly IBrush RestArc = NotaPalette.VizInk; // a value at restprivate static readonly IBrush LiveArc = NotaPalette.Accent; // the value while it is being set+ private static readonly IBrush TickInk = NotaPalette.TextTertiary; // a second value of the param (OtherValue)private static readonly IBrush Cap = NotaPalette.SurfaceRaised;private static readonly IBrush CapEdge = NotaPalette.Seam;private static readonly IBrush CapEdgeOff = NotaPalette.Seam;@@ -79,6 +80,16 @@ public sealed class Knob : Controlpublic bool IsDim { get => _dim; set { if (_dim == value) return; _dim = value; InvalidateVisual(); } }private bool _dim;+ /// <summary>A second value of the same parameter shown as a tick outside the groove — Nota+ /// Twin's other morph side (0..max; NaN = none).</summary>+ public double OtherValue { get => _other; set { if (_other.Equals(value)) return; _other = value; InvalidateVisual(); } }+ private double _other = double.NaN;++ /// <summary>The value the sound is at right now, when that differs from the knob's own —+ /// Nota Twin's morphed value — drawn as a dot on the groove (0..max; NaN = none).</summary>+ public double SoundingValue { get => _sounding; set { if (_sounding.Equals(value)) return; _sounding = value; InvalidateVisual(); } }+ private double _sounding = double.NaN;+/// <summary>Value restored on double-click (NaN = no reset).</summary>public double Default { get; set; } = double.NaN;@@ -231,6 +242,21 @@ public sealed class Knob : Controlif (frac > 0.001)ctx.DrawGeometry(null, new Pen(arcBrush, sw, lineCap: PenLineCap.Round), Arc(cx, cy, r, 0, frac));+ // The other side's value: a tick just outside the groove.+ if (!double.IsNaN(_other) && _max > 0 && Math.Abs(_other - _value) > 0.002 * _max)+ {+ double ao = (StartDeg + Math.Clamp(_other / _max, 0, 1) * SweepDeg) * Math.PI / 180.0;+ double r0 = r + sw * 0.7, r1 = r + sw * 1.7;+ ctx.DrawLine(new Pen(on ? TickInk : PointerOff, Math.Max(1, sw * 0.45), lineCap: PenLineCap.Round),+ new Point(cx + Math.Cos(ao) * r0, cy + Math.Sin(ao) * r0), new Point(cx + Math.Cos(ao) * r1, cy + Math.Sin(ao) * r1));+ }+ // Where the sound is now (live): a dot riding the groove.+ if (!double.IsNaN(_sounding) && _max > 0 && on)+ {+ double asd = (StartDeg + Math.Clamp(_sounding / _max, 0, 1) * SweepDeg) * Math.PI / 180.0;+ ctx.DrawEllipse(LiveArc, null, new Point(cx + Math.Cos(asd) * r, cy + Math.Sin(asd) * r), sw * 0.55, sw * 0.55);+ }+// Raised face with a 1px seam edge.ctx.DrawEllipse(Cap, new Pen(on ? CapEdge : CapEdgeOff, 1), new Point(cx, cy), CapR * k, CapR * k);diff --git a/src/managed/Nota.App/Controls/TwinViews.cs b/src/managed/Nota.App/Controls/TwinViews.csnew file mode 100644index 00000000..2781f0ee--- /dev/null+++ b/src/managed/Nota.App/Controls/TwinViews.cs@@ -0,0 +1,962 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Detail · Devices — Nota Twin's own views (specs/055).+//+// TwinExpressionPad: the three-axis expression pad (FR-031), a mouse player's stand-in for a+// pressure-sensitive surface. Drag moves X (left → right) and Y (bottom → top); holding the+// button down raises Z — the "press" — over half a second, and letting go lets it fall back over+// a quarter. The axes are ordinary params (pad X / Y / Z), so they automate and learn like any+// knob; the card names what each one drives. It is a graph window (NotaGraph): well, hairline,+// crosshair in the grid colour; the point is neutral ink at rest and the accent while held, with+// a ring that grows with Z. Left button only; double-click centres X / Y.++using System;+using System.Collections.Generic;+using System.Globalization;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using Avalonia.Media;+using Avalonia.Threading;++namespace Nota.App;++internal sealed class TwinExpressionPad : Control+{+ private const double RiseSec = 0.5, FallSec = 0.25;+ private double _x = 0.5, _y = 0.5, _z;+ private bool _drag;+ private readonly DispatcherTimer _tick;+ private DateTime _last;++ /// <summary>X and Y moved by hand (0..1, Y up).</summary>+ public Action<double, double>? XyChanged;+ /// <summary>Z moved by the hold (0..1).</summary>+ public Action<double>? ZChanged;+ public Action? GestureBegin;+ public Action? GestureEnd;+ /// <summary>Double-click: X and Y back to the centre.</summary>+ public Action? Reset;++ public TwinExpressionPad()+ {+ ClipToBounds = true;+ Cursor = new Cursor(StandardCursorType.Hand);+ DoubleTapped += (_, e) => { Reset?.Invoke(); e.Handled = true; };+ _tick = new DispatcherTimer(TimeSpan.FromMilliseconds(16), DispatcherPriority.Input, (_, _) => Step());+ }++ public bool Dragging => _drag || _tick.IsEnabled;++ /// <summary>Follow the params (automation, another view) without firing anything.</summary>+ public void SetValues(double x, double y, double z)+ {+ if (Dragging) return;+ _x = Math.Clamp(x, 0, 1); _y = Math.Clamp(y, 0, 1); _z = Math.Clamp(z, 0, 1);+ InvalidateVisual();+ }++ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return; // right-click bubbles+ if (e.ClickCount > 1) return; // DoubleTapped resets+ if (!_tick.IsEnabled) GestureBegin?.Invoke();+ _drag = true;+ e.Pointer.Capture(this);+ Apply(e.GetPosition(this));+ _last = DateTime.UtcNow;+ _tick.Start();+ e.Handled = true;+ }+ protected override void OnPointerMoved(PointerEventArgs e)+ {+ if (_drag) Apply(e.GetPosition(this));+ }+ protected override void OnPointerReleased(PointerReleasedEventArgs e)+ {+ if (!_drag) return;+ _drag = false;+ e.Pointer.Capture(null);+ InvalidateVisual();+ }+ protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e)+ {+ _drag = false;+ InvalidateVisual();+ }++ // Z rises while held and falls once let go; the gesture ends when it has settled at 0.+ private void Step()+ {+ var now = DateTime.UtcNow;+ double dt = (now - _last).TotalSeconds;+ _last = now;+ double z = _drag ? Math.Min(1, _z + dt / RiseSec) : Math.Max(0, _z - dt / FallSec);+ if (z != _z) { _z = z; ZChanged?.Invoke(z); InvalidateVisual(); }+ if (!_drag && _z <= 0)+ {+ _tick.Stop();+ GestureEnd?.Invoke();+ }+ }++ private void Apply(Point p)+ {+ double w = Math.Max(1, Bounds.Width), h = Math.Max(1, Bounds.Height);+ _x = Math.Clamp(p.X / w, 0, 1);+ _y = 1 - Math.Clamp(p.Y / h, 0, 1);+ InvalidateVisual();+ XyChanged?.Invoke(_x, _y);+ }++ public override void Render(DrawingContext ctx)+ {+ var r = new Rect(Bounds.Size);+ if (r.Width < 8 || r.Height < 8) return;+ NotaGraph.Window(ctx, r);+ ctx.DrawLine(NotaGraph.GridPen, new Point(Math.Round(r.Width / 2) + 0.5, 1), new Point(Math.Round(r.Width / 2) + 0.5, r.Height - 1));+ ctx.DrawLine(NotaGraph.GridPen, new Point(1, Math.Round(r.Height / 2) + 0.5), new Point(r.Width - 1, Math.Round(r.Height / 2) + 0.5));+ Label(ctx, "X", r.Width - 6, r.Height / 2 + 2, true);+ Label(ctx, "Y", r.Width / 2 + 4, 3, false);++ var p = new Point(_x * r.Width, (1 - _y) * r.Height);+ bool live = _drag || _z > 0;+ if (_z > 0.001)+ ctx.DrawEllipse(null, new Pen(NotaPalette.Accent, 1.5), p, 7 + 12 * _z, 7 + 12 * _z);+ ctx.DrawEllipse(live ? NotaPalette.Accent : NotaPalette.VizInk, new Pen(NotaPalette.BgSunken, 2), p, 6, 6);+ }++ private static void Label(DrawingContext ctx, string text, double x, double y, bool rightAlign)+ {+ var ft = new FormattedText(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, NotaFonts.SansMedium, NotaType.KnobLabel, NotaPalette.TextTertiary);+ ctx.DrawText(ft, new Point(rightAlign ? x - ft.Width : x, y));+ }+}++// A graph on Twin params: reads and writes them by id (the card binds them to the side being+// edited) and frames each drag as an automation-write gesture.+internal abstract class TwinParamGraph : Control+{+ public Func<string, float> Get = _ => 0f;+ public Action<string, float>? Set;+ public Action<string>? Begin, End;+ protected string Prefix = "";+ private string[] _drag = Array.Empty<string>();++ protected TwinParamGraph() { ClipToBounds = true; }++ public void Bind(string prefix) { Prefix = prefix; InvalidateVisual(); }+ public void Refresh() => InvalidateVisual();+ public bool Dragging => _drag.Length > 0;+ protected float P(string id) => Get(Prefix + id);+ protected void Write(string id, double v) { Set?.Invoke(Prefix + id, (float)Math.Clamp(v, 0, 1)); InvalidateVisual(); }++ // Which params a press at `p` grabs (none = not interactive there).+ protected virtual string[] Grab(Point p) => Array.Empty<string>();+ protected virtual void Drag(Point p) { }++ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ if (Set is null || !e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;+ var p = e.GetPosition(this);+ _drag = Grab(p);+ if (_drag.Length == 0) return;+ foreach (var id in _drag) Begin?.Invoke(Prefix + id);+ e.Pointer.Capture(this);+ Drag(p);+ e.Handled = true;+ }+ protected override void OnPointerMoved(PointerEventArgs e) { if (_drag.Length > 0) Drag(e.GetPosition(this)); }+ protected override void OnPointerReleased(PointerReleasedEventArgs e) => Finish(e.Pointer);+ protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e) => Finish(null);+ private void Finish(IPointer? ptr)+ {+ if (_drag.Length == 0) return;+ foreach (var id in _drag) End?.Invoke(Prefix + id);+ _drag = Array.Empty<string>();+ ptr?.Capture(null);+ InvalidateVisual();+ }+ protected static StreamGeometry Path(Point[] pts)+ {+ var g = new StreamGeometry();+ using var c = g.Open();+ c.BeginFigure(pts[0], false);+ for (int i = 1; i < pts.Length; i++) c.LineTo(pts[i]);+ c.EndFigure(false);+ return g;+ }+}++// One cycle of an oscillator as the voice makes it: triangle → saw → square by Wave, the pulse+// width, Metal folding the triangle share. Drag sideways to move Wave.+internal sealed class TwinWaveView : TwinParamGraph+{+ private readonly string _o;+ public TwinWaveView(int osc) { _o = $"o{osc}"; Cursor = new Cursor(StandardCursorType.SizeWestEast); }+ protected override string[] Grab(Point p) => new[] { _o + "wave" };+ protected override void Drag(Point p) => Write(_o + "wave", p.X / Math.Max(1, Bounds.Width));++ public static double Sample(double ph, double w, double pw, double metal)+ {+ double gt = Math.Max(0, 1 - 2 * w), gs = 1 - Math.Abs(2 * w - 1), gp = 0.6 * Math.Max(0, 2 * w - 1);+ double duty = 0.05 + 0.9 * pw;+ double tri = ph < 0.5 ? 4 * ph - 1 : 3 - 4 * ph, saw = 2 * ph - 1, pul = (ph < duty ? 1 : -1) - (2 * duty - 1);+ double y = gt * tri + gs * saw + gp * pul;+ double m = metal * gt;+ if (m > 0) y += m * (Math.Sin(Math.PI / 2 * (1 + 3 * m) * y) - y);+ return y;+ }++ public override void Render(DrawingContext ctx)+ {+ var r = new Rect(Bounds.Size);+ if (r.Width < 8) return;+ NotaGraph.Window(ctx, r);+ double w = P(_o + "wave"), pw = P(_o + "pw"), mt = P(_o + "metal");+ int n = (int)r.Width;+ var pts = new Point[n];+ for (int i = 0; i < n; i++)+ {+ double y = Sample(i / (double)(n - 1), w, pw, mt);+ pts[i] = new Point(i, r.Height / 2 - y * (r.Height / 2 - 3) / 1.2);+ }+ ctx.DrawGeometry(null, Dragging ? NotaGraph.SecondaryPen(NotaPalette.Accent, 1.4) : NotaGraph.SecondaryPen(NotaPalette.VizInk, 1.2), Path(pts));+ }+}++// The two filters' combined response, as the route and Osc 1's balance put them together: the+// multimode (teal) and the ladder (rose) faint, their sum in viz ink. Drag sets the ladder's+// cutoff (x) and resonance (y).+internal sealed class TwinFilterView : TwinParamGraph+{+ private const double DbTop = 18, DbBottom = -36;+ public TwinFilterView() { Cursor = new Cursor(StandardCursorType.Hand); }+ protected override string[] Grab(Point p) => new[] { "ldcut", "ldres" };+ protected override void Drag(Point p)+ {+ Write("ldcut", p.X / Math.Max(1, Bounds.Width));+ Write("ldres", 1 - p.Y / Math.Max(1, Bounds.Height));+ }++ // Magnitudes at a frequency (normalized 0..1 on the 20 Hz … 20 kHz axis).+ private (double Mm, double Ld, double Sum) At(double x)+ {+ double f = 20 * Math.Pow(1000, x);+ double fm = 20 * Math.Pow(1000, P("mmcut")), fl = 20 * Math.Pow(1000, P("ldcut"));+ // Multimode: the 2-pole state-variable core, its mode a blend of LP / BP / HP / notch.+ var s = new System.Numerics.Complex(0, f / fm);+ double k = 2 - 2.04 * P("mmres");+ var den = s * s + k * s + 1;+ System.Numerics.Complex lp = 1 / den, bp = s / den, hp = s * s / den;+ double m = Math.Clamp(P("mmmode"), 0, 1) * 3;+ System.Numerics.Complex hm = m < 1 ? lp * (1 - m) + bp * (1.6 * m)+ : m < 2 ? bp * (1.6 * (2 - m)) + hp * (m - 1) : hp + lp * (m - 2);+ // Ladder: four one-poles in a resonant loop; the 12 dB tap after the second.+ var g = 1 / (1 + new System.Numerics.Complex(0, f / fl));+ double kl = 4 * Math.Clamp(P("ldres"), 0, 1);+ var g4 = g * g * g * g;+ var hl = (P("ldslope") >= 0.5f ? g4 : g * g) / (1 + kl * g4);+ double b = P("o1bal"), rt = P("route");+ var sum = hl * (b + (1 - rt) * (1 - b) * hm) + rt * (1 - b) * hm;+ return (hm.Magnitude, hl.Magnitude, sum.Magnitude);+ }++ public override void Render(DrawingContext ctx)+ {+ var r = new Rect(Bounds.Size);+ if (r.Width < 16) return;+ NotaGraph.Window(ctx, r);+ double Y(double mag) => Math.Clamp((DbTop - 20 * Math.Log10(Math.Max(mag, 1e-6))) / (DbTop - DbBottom), 0, 1) * r.Height;+ for (int dec = 1; dec < 3; dec++) // 200 Hz, 2 kHz+ {+ double gx = Math.Round(dec / 3.0 * r.Width) + 0.5;+ ctx.DrawLine(NotaGraph.GridPen, new Point(gx, 1), new Point(gx, r.Height - 1));+ }+ double y0 = Math.Round(Y(1)) + 0.5;+ ctx.DrawLine(NotaGraph.GridPen, new Point(1, y0), new Point(r.Width - 1, y0));+ int n = (int)r.Width;+ Point[] mm = new Point[n], ld = new Point[n], sum = new Point[n];+ for (int i = 0; i < n; i++)+ {+ var (a, bl, c) = At(i / (double)(n - 1));+ mm[i] = new Point(i, Y(a)); ld[i] = new Point(i, Y(bl)); sum[i] = new Point(i, Y(c));+ }+ ctx.DrawGeometry(null, NotaGraph.SecondaryPen(NotaPalette.Teal, 1.0), Path(mm));+ ctx.DrawGeometry(null, NotaGraph.SecondaryPen(NotaPalette.Rose, 1.0), Path(ld));+ ctx.DrawGeometry(null, NotaGraph.PrimaryPen, Path(sum));+ NotaGraph.Node(ctx, new Point(P("ldcut") * r.Width, (1 - P("ldres")) * r.Height), Dragging);+ NotaGraph.Axis(ctx, r, NotaGraph.Corner.BottomLeft, "20");+ NotaGraph.Axis(ctx, r, NotaGraph.Corner.BottomRight, "20k");+ }+}++// An envelope: delay (mod env), attack, decay to the sustain level, a held stretch, release —+// each time on its own stretch of the width, so a handle never jumps while another moves.+// Handles: the attack peak (A), the decay corner (D and S), the release end (R).+internal sealed class TwinEnvView : TwinParamGraph+{+ private readonly string _e;+ private readonly bool _delay;+ public TwinEnvView(string env, bool delay) { _e = env; _delay = delay; Cursor = new Cursor(StandardCursorType.Hand); }++ private double Seg => Bounds.Width * (_delay ? 0.22 : 0.27);+ private double Dly => _delay ? P(_e + "dly") * Bounds.Width * 0.12 : 0;+ private Point[] Handles()+ {+ double h = Bounds.Height - 4, top = 3;+ double xa = Dly + P(_e + "a") * Seg, xd = xa + P(_e + "d") * Seg, xs = xd + Bounds.Width * 0.16, xr = xs + P(_e + "r") * Seg;+ double ys = top + (1 - P(_e + "s")) * h;+ return new[] { new Point(xa, top), new Point(xd, ys), new Point(Math.Min(xr, Bounds.Width - 2), top + h) };+ }+ private int _which = -1;+ protected override string[] Grab(Point p)+ {+ var hs = Handles();+ _which = 0;+ double best = double.MaxValue;+ for (int i = 0; i < hs.Length; i++)+ {+ double d = Math.Abs(hs[i].X - p.X) + 0.5 * Math.Abs(hs[i].Y - p.Y);+ if (d < best) { best = d; _which = i; }+ }+ return _which switch { 0 => new[] { _e + "a" }, 1 => new[] { _e + "d", _e + "s" }, _ => new[] { _e + "r" } };+ }+ protected override void Drag(Point p)+ {+ var hs = Handles();+ double h = Bounds.Height - 4;+ switch (_which)+ {+ case 0: Write(_e + "a", (p.X - Dly) / Seg); break;+ case 1: Write(_e + "d", (p.X - hs[0].X) / Seg); Write(_e + "s", 1 - (p.Y - 3) / h); break;+ default: Write(_e + "r", (p.X - (hs[1].X + Bounds.Width * 0.16)) / Seg); break;+ }+ }++ public override void Render(DrawingContext ctx)+ {+ var r = new Rect(Bounds.Size);+ if (r.Width < 16) return;+ NotaGraph.Window(ctx, r);+ var hs = Handles();+ double bottom = r.Height - 1;+ double curve = _e == "menv" ? 0.5 : P(_e + "curve");+ double k = 0.4 + 5 * curve; // the attack's bow, as the curve sets the analog overshoot+ var pts = new System.Collections.Generic.List<Point> { new(1, bottom), new(Dly, bottom) };+ for (int i = 1; i <= 16; i++)+ {+ double t = i / 16.0;+ pts.Add(new Point(Dly + (hs[0].X - Dly) * t, bottom - (bottom - hs[0].Y) * (1 - Math.Exp(-k * t)) / (1 - Math.Exp(-k))));+ }+ for (int i = 1; i <= 16; i++)+ {+ double t = i / 16.0;+ pts.Add(new Point(hs[0].X + (hs[1].X - hs[0].X) * t, hs[1].Y + (hs[0].Y - hs[1].Y) * Math.Exp(-4 * t)));+ }+ double xs = hs[1].X + r.Width * 0.16;+ pts.Add(new Point(xs, hs[1].Y));+ for (int i = 1; i <= 16; i++)+ {+ double t = i / 16.0;+ pts.Add(new Point(xs + (hs[2].X - xs) * t, bottom - (bottom - hs[1].Y) * Math.Exp(-4 * t)));+ }+ ctx.DrawGeometry(null, NotaGraph.PrimaryPen, Path(pts.ToArray()));+ foreach (var hp in hs) NotaGraph.Node(ctx, hp, Dragging);+ }+}++// One cycle of an LFO's shape, with where it is now (the instrument's live phase).+internal sealed class TwinLfoView : TwinParamGraph+{+ private readonly int _l;+ public double Phase = -1;+ public TwinLfoView(int lfo) { _l = lfo; }++ private static double Shape(int shape, double p, double sym)+ {+ switch (shape)+ {+ case 0: return Math.Sin(2 * Math.PI * p);+ case 1: return p < sym ? 2 * p / Math.Max(sym, 1e-3) - 1 : 1 - 2 * (p - sym) / Math.Max(1 - sym, 1e-3);+ case 2: return 1 - 2 * p;+ case 3: return p < 0.5 ? 1 : -1;+ case 4: { int s = (int)(p * 4); return new[] { 0.6, -0.4, 0.9, -0.8 }[s % 4]; }+ default:+ {+ double[] v = { 0.6, -0.4, 0.9, -0.8, 0.6 };+ double x = p * 4; int s = (int)x; double t = x - s; t = t * t * (3 - 2 * t);+ return v[s] + (v[Math.Min(4, s + 1)] - v[s]) * t;+ }+ }+ }++ public override void Render(DrawingContext ctx)+ {+ var r = new Rect(Bounds.Size);+ if (r.Width < 16) return;+ NotaGraph.Window(ctx, r);+ string l = $"lfo{_l}";+ int shape = Math.Clamp((int)Math.Round(P(l + "shape") * 5), 0, 5);+ double sym = _l == 3 ? Math.Clamp(P("lfo3sym"), 0.02, 0.98) : 0.5;+ double ex = _l == 3 ? Math.Pow(2, (P("lfo3curve") - 0.5) * 4) : 1;+ ctx.DrawLine(NotaGraph.GridPen, new Point(1, Math.Round(r.Height / 2) + 0.5), new Point(r.Width - 1, Math.Round(r.Height / 2) + 0.5));+ int n = (int)r.Width;+ var pts = new Point[n];+ for (int i = 0; i < n; i++)+ {+ double y = Shape(shape, i / (double)(n - 1), sym);+ y = Math.Sign(y) * Math.Pow(Math.Abs(y), ex);+ pts[i] = new Point(i, r.Height / 2 - y * (r.Height / 2 - 4));+ }+ ctx.DrawGeometry(null, NotaGraph.PrimaryPen, Path(pts));+ if (Phase >= 0)+ {+ double x = Math.Round(Phase * (r.Width - 1)) + 0.5;+ ctx.DrawLine(new Pen(NotaPalette.Accent, 1), new Point(x, 2), new Point(x, r.Height - 2));+ }+ }+}++// The part's morph as it sounds now (the accent mark) and each sounding voice's own morph (dots),+// on a strip from A (left) to B (right).+internal sealed class TwinMorphStrip : Control+{+ private double _part = -1;+ private readonly double[] _voices = new double[12];+ public void Set(double part, ReadOnlySpan<float> voices)+ {+ _part = part;+ for (int i = 0; i < _voices.Length; i++) _voices[i] = i < voices.Length ? voices[i] : -1;+ InvalidateVisual();+ }+ public override void Render(DrawingContext ctx)+ {+ var r = new Rect(Bounds.Size);+ if (r.Width < 8) return;+ double y = r.Height / 2;+ ctx.DrawLine(new Pen(NotaPalette.BgSunken, 3, lineCap: PenLineCap.Round), new Point(3, y), new Point(r.Width - 3, y)); // the groove+ foreach (var v in _voices)+ if (v >= 0) ctx.DrawEllipse(NotaPalette.VizInk, null, new Point(3 + v * (r.Width - 6), y), 2, 2);+ if (_part >= 0)+ {+ double x = 3 + _part * (r.Width - 6);+ ctx.DrawLine(new Pen(NotaPalette.Accent, 2, lineCap: PenLineCap.Round), new Point(x, 1), new Point(x, r.Height - 1));+ }+ }+}++// The sequencer's steps, a page of sixteen: each cell shows its notes, a velocity bar (drag up /+// down) and a gate bar along the bottom (drag sideways; past the edge it ties into the next step).+// A drag edits a preview and commits once, on release — one undo step per gesture. The playing+// step is marked in the accent, the step-record cursor and the selection in ink; a motion lane's+// values ride as teal ticks.+internal sealed class TwinStepGrid : Control+{+ public Nota.Application.Twin.TwinPatterns.Pattern? Pattern;+ public int Page, PlayStep = -1, RecStep = -1, Selected = -1, Lane = 0;+ public Action<int>? SelectStep;+ public Action<int, int>? CommitVelocity; // step, 1..127+ public Action<int, int>? CommitGate; // step, 1..100 or GateTie++ private int _drag = -1;+ private bool _gate;+ private int _vel, _gt;++ public TwinStepGrid() { ClipToBounds = true; Cursor = new Cursor(StandardCursorType.Hand); }++ private double CellW => Bounds.Width / 16.0;+ private int StepAt(Point p) => Page * 16 + Math.Clamp((int)(p.X / CellW), 0, 15);++ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ if (Pattern is null || !e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;+ var p = e.GetPosition(this);+ int st = StepAt(p);+ if (st >= Pattern.Length) return;+ Selected = st;+ SelectStep?.Invoke(st);+ var s = Pattern.Steps[st];+ _gate = p.Y > Bounds.Height - 14;+ _vel = s.Velocity;+ _gt = s.Gate;+ _drag = s.IsRest ? -1 : st;+ if (_drag >= 0) { e.Pointer.Capture(this); Move(p); }+ InvalidateVisual();+ e.Handled = true;+ }+ protected override void OnPointerMoved(PointerEventArgs e) { if (_drag >= 0) Move(e.GetPosition(this)); }+ private void Move(Point p)+ {+ double x0 = (_drag - Page * 16) * CellW;+ if (_gate)+ {+ double f = (p.X - x0) / CellW;+ _gt = f > 1.05 ? Nota.Application.Twin.TwinPatterns.GateTie : Math.Clamp((int)Math.Round(f * 100), 1, 100);+ }+ else+ {+ double top = 18, h = Bounds.Height - 18 - 16;+ _vel = Math.Clamp((int)Math.Round((1 - (p.Y - top) / h) * 127), 1, 127);+ }+ InvalidateVisual();+ }+ protected override void OnPointerReleased(PointerReleasedEventArgs e)+ {+ if (_drag < 0) return;+ int st = _drag;+ _drag = -1;+ e.Pointer.Capture(null);+ if (_gate) CommitGate?.Invoke(st, _gt); else CommitVelocity?.Invoke(st, _vel);+ }++ public override void Render(DrawingContext ctx)+ {+ var r = new Rect(Bounds.Size);+ if (r.Width < 32) return;+ NotaGraph.Window(ctx, r);+ if (Pattern is null) return;+ double cw = CellW, top = 18, barH = r.Height - top - 16;+ var mono = NotaFonts.Mono;+ for (int c = 0; c < 16; c++)+ {+ int st = Page * 16 + c;+ double x = c * cw;+ if (c > 0) ctx.DrawLine(NotaGraph.GridPen, new Point(Math.Round(x) + 0.5, 2), new Point(Math.Round(x) + 0.5, r.Height - 2));+ if (st >= Pattern.Length) { ctx.FillRectangle(NotaPalette.SurfaceAbyss, new Rect(x + 1, 1, cw - 1, r.Height - 2)); continue; }+ var s = Pattern.Steps[st];+ bool dragging = st == _drag;+ int vel = dragging && !_gate ? _vel : s.Velocity, gate = dragging && _gate ? _gt : s.Gate;+ if (st == PlayStep) ctx.FillRectangle(NotaPalette.Accent, new Rect(x + 2, 2, cw - 4, 2));+ if (!s.IsRest)+ {+ string label = Nota.Application.Twin.TwinPatterns.NoteName(s.Notes[0]) + (s.Notes.Count > 1 ? $"+{s.Notes.Count - 1}" : "");+ var ft = new FormattedText(label, System.Globalization.CultureInfo.InvariantCulture, FlowDirection.LeftToRight, mono, 7.5, NotaPalette.TextSecondary);+ ctx.DrawText(ft, new Point(x + Math.Max(1, (cw - ft.Width) / 2), 5));+ double vh = barH * vel / 127.0;+ ctx.FillRectangle(dragging ? NotaPalette.Accent : NotaPalette.VizInk, new Rect(x + cw * 0.3, top + barH - vh, cw * 0.4, vh));+ bool tie = gate >= Nota.Application.Twin.TwinPatterns.GateTie;+ double gw = tie ? cw : cw * gate / 100.0;+ ctx.FillRectangle(tie ? NotaPalette.Teal : NotaPalette.TextTertiary, new Rect(x + 1, r.Height - 9, Math.Max(2, gw - 1), 4));+ }+ var lane = Pattern.Lanes[Math.Clamp(Lane, 0, 3)];+ if (lane.Target >= 0 && lane.Values[st] != Nota.Application.Twin.TwinPatterns.MotionUnset)+ {+ double y = top + barH * (1 - lane.Values[st] / 65534.0);+ ctx.DrawLine(new Pen(NotaPalette.Teal, 1.5), new Point(x + 3, y), new Point(x + cw - 3, y));+ }+ if (st == RecStep || st == Selected)+ ctx.DrawRectangle(null, new Pen(st == RecStep ? NotaPalette.Accent : NotaPalette.TextSecondary, 1), new Rect(x + 1.5, 1.5, cw - 3, r.Height - 3));+ }+ }+}++// How the two filters are wired, as the route puts them: series (multi → ladder) on the left+// of the slider, parallel (both side by side, summed) on the right; between, the share that runs+// in parallel. Read-only — the route slider above it moves it.+internal sealed class TwinRouteView : TwinParamGraph+{+ public override void Render(DrawingContext ctx)+ {+ var r = new Rect(Bounds.Size);+ if (r.Width < 40 || r.Height < 30) return;+ NotaGraph.Window(ctx, r);+ double rt = P("route");+ NotaGraph.Axis(ctx, r, NotaGraph.Corner.TopLeft, rt <= 0.01 ? "series" : rt >= 0.99 ? "parallel" : $"{NotaNum.Pct((float)rt)} parallel");+ var pen = NotaGraph.SecondaryPen(NotaPalette.VizInk, 1.0);+ const double bw = 30, bh = 13;+ double mid = Math.Round(r.Height / 2 + 4) + 0.5, cx = Math.Round(r.Width / 2);+ void Box(double x, double y, string name)+ {+ var b = new Rect(Math.Round(x) + 0.5, Math.Round(y) + 0.5, bw, bh);+ ctx.DrawRectangle(null, pen, b, 2, 2);+ var ft = NotaGraph.AxisText(name, NotaPalette.TextSecondary);+ ctx.DrawText(ft, new Point(b.X + (bw - ft.Width) / 2, b.Y + (bh - ft.Height) / 2));+ }+ if (rt >= 0.5)+ {+ double top = mid - 10, bot = mid + 10, l = 8, rr = r.Width - 8;+ ctx.DrawLine(pen, new Point(4, mid), new Point(l, mid));+ ctx.DrawLine(pen, new Point(l, top), new Point(l, bot));+ ctx.DrawLine(pen, new Point(rr, top), new Point(rr, bot));+ ctx.DrawLine(pen, new Point(rr, mid), new Point(r.Width - 4, mid));+ foreach (var y in new[] { top, bot })+ {+ ctx.DrawLine(pen, new Point(l, y), new Point(cx - bw / 2, y));+ ctx.DrawLine(pen, new Point(cx + bw / 2, y), new Point(rr, y));+ }+ Box(cx - bw / 2, top - bh / 2, "multi");+ Box(cx - bw / 2, bot - bh / 2, "ladder");+ }+ else+ {+ double a = cx - bw - 4, b = cx + 4;+ ctx.DrawLine(pen, new Point(4, mid), new Point(a, mid));+ ctx.DrawLine(pen, new Point(a + bw, mid), new Point(b, mid));+ ctx.DrawLine(pen, new Point(b + bw, mid), new Point(r.Width - 4, mid));+ Box(a, mid - bh / 2, "multi");+ Box(b, mid - bh / 2, "ladder");+ }+ }+}++// A read-only picture of one of the part's effects, from its own params: the mod-FX sweep+// (rate and depth; three phases for the ensemble), the delay's taps (time or division,+// feedback, ping-pong above / below the line for left / right) or the reverb's tail (size and+// damping). Off draws in the rule colour.+internal sealed class TwinFxView : TwinParamGraph+{+ public enum Kind { ModFx, Delay, Reverb }+ private static readonly double[] DivBeats = { 0.25, 1 / 3.0, 0.5, 0.75, 2 / 3.0, 1, 1.5, 2 };+ private readonly Kind _kind;+ public TwinFxView(Kind kind) { _kind = kind; }++ public override void Render(DrawingContext ctx)+ {+ var r = new Rect(Bounds.Size);+ if (r.Width < 24 || r.Height < 16) return;+ NotaGraph.Window(ctx, r);+ string on = _kind switch { Kind.ModFx => "modfxon", Kind.Delay => "dlyon", _ => "revon" };+ IBrush ink = P(on) >= 0.5f ? NotaPalette.VizInk : NotaPalette.Rule;+ var pen = NotaGraph.SecondaryPen(ink, 1.2);+ double mid = Math.Round(r.Height / 2) + 0.5;+ switch (_kind)+ {+ case Kind.ModFx:+ {+ ctx.DrawLine(NotaGraph.GridPen, new Point(1, mid), new Point(r.Width - 1, mid));+ double cycles = 1 + 4 * P("modfxrate"), depth = 0.15 + 0.85 * P("modfxdepth");+ int type = Math.Clamp((int)Math.Round(P("modfxtype") * 3), 0, 3), phases = type == 3 ? 3 : 1;+ int n = Math.Max(2, (int)r.Width - 6);+ for (int k = 0; k < phases; k++)+ {+ var pts = new Point[n];+ for (int i = 0; i < n; i++)+ {+ double x = i / (double)(n - 1);+ pts[i] = new Point(3 + i, mid - Math.Sin(2 * Math.PI * (x * cycles + k / 3.0)) * depth * (r.Height / 2 - 4));+ }+ ctx.DrawGeometry(null, k == 0 ? pen : NotaGraph.SecondaryPen(ink, 0.8), Path(pts));+ }+ NotaGraph.Axis(ctx, r, NotaGraph.Corner.TopRight, "sweep");+ break;+ }+ case Kind.Delay:+ {+ ctx.DrawLine(NotaGraph.GridPen, new Point(1, mid), new Point(r.Width - 1, mid));+ // Two seconds across, at 120 BPM for a synced division.+ double sec = P("dlysync") >= 0.5f ? DivBeats[Math.Clamp((int)Math.Round(P("dlydiv") * 7), 0, 7)] * 0.5 : Math.Max(0.001, P("dlytime") * 2.0);+ double step = Math.Max(4, sec / 2.0 * (r.Width - 8)), fb = P("dlyfb"), amp = 0.8, h = r.Height / 2 - 4;+ bool ping = P("dlypingpong") >= 0.5f;+ ctx.DrawRectangle(NotaPalette.TextFaint, null, new Rect(4, mid - h, 2, h), 1, 1);+ for (int i = 1; 4 + i * step < r.Width - 4 && amp > 0.03; i++, amp *= Math.Max(0.05, fb))+ {+ double x = Math.Round(4 + i * step), hh = Math.Max(1, amp * h);+ bool up = !ping || i % 2 == 1;+ ctx.DrawRectangle(ink, null, new Rect(x, up ? mid - hh : mid, 2, hh), 1, 1);+ }+ NotaGraph.Axis(ctx, r, NotaGraph.Corner.TopRight, "L");+ NotaGraph.Axis(ctx, r, NotaGraph.Corner.BottomRight, "R");+ break;+ }+ default:+ {+ double size = 0.3 + 3 * P("revsize"), damp = P("revdamp");+ int n = Math.Max(2, (int)r.Width - 8);+ var pts = new Point[n];+ for (int i = 0; i < n; i++)+ {+ double t = i / (double)(n - 1) * 4; // four seconds across+ double lvl = Math.Exp(-t * (1 + 1.5 * damp) / size);+ pts[i] = new Point(4 + i, 4 + (1 - lvl) * (r.Height - 8));+ }+ ctx.DrawGeometry(null, pen, Path(pts));+ NotaGraph.Axis(ctx, r, NotaGraph.Corner.TopRight, "tail");+ break;+ }+ }+ }+}++// A number in a well that drags like a knob: vertical, up increases, the full range over 140 px,+// Shift / Ctrl / ⌘ fine; a click never jumps it; double-click restores the default; left button+// only, so right-click reaches the parameter menu. The number is in Ink 1 at rest and the+// accent while hovered or dragged. Used where a row of four knobs will not fit — the ADSR times+// under Twin's envelope graphs.+internal sealed class TwinValueWell : Border+{+ private readonly TextBlock _text = new()+ {+ FontFamily = NotaFonts.MonoFamily, FontSize = NotaType.KnobValue, Foreground = NotaPalette.TextPrimary,+ HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center,+ };+ private double _value, _lastY;+ private bool _drag;+ public Func<double, string> Format = v => NotaNum.Pct((float)v);+ public double Default = double.NaN;+ public event Action<double>? ValueChanged;+ public event Action? GestureBegin, GestureEnd;+ public bool Dragging => _drag;+ public TextBlock Readout => _text;++ public TwinValueWell()+ {+ Height = 15;+ Background = NotaPalette.BgSunken;+ BorderBrush = NotaPalette.Rule;+ BorderThickness = new Thickness(1);+ CornerRadius = NotaRadius.Clip;+ Cursor = new Cursor(StandardCursorType.SizeNorthSouth);+ Child = _text;+ PointerEntered += (_, _) => Paint();+ PointerExited += (_, _) => Paint();+ }++ public double Value+ {+ get => _value;+ set { _value = Math.Clamp(value, 0, 1); _text.Text = Format(_value); }+ }++ private void Paint() => _text.Foreground = _drag || IsPointerOver ? NotaPalette.Accent : NotaPalette.TextPrimary;++ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ var pt = e.GetCurrentPoint(this);+ if (!pt.Properties.IsLeftButtonPressed) return;+ if (e.ClickCount == 2 && !double.IsNaN(Default))+ {+ GestureBegin?.Invoke(); Value = Default; ValueChanged?.Invoke(_value); GestureEnd?.Invoke();+ e.Handled = true;+ return;+ }+ _drag = true; _lastY = pt.Position.Y;+ e.Pointer.Capture(this);+ GestureBegin?.Invoke();+ Paint();+ e.Handled = true;+ }++ protected override void OnPointerMoved(PointerEventArgs e)+ {+ if (!_drag) return;+ double y = e.GetPosition(this).Y, dy = _lastY - y;+ _lastY = y;+ bool fine = (e.KeyModifiers & (KeyModifiers.Shift | KeyModifiers.Control | KeyModifiers.Meta)) != 0;+ Value = _value + dy / 140.0 * (fine ? 0.1 : 1);+ ValueChanged?.Invoke(_value);+ }++ protected override void OnPointerReleased(PointerReleasedEventArgs e) => Finish(e.Pointer);+ protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e) => Finish(null);+ private void Finish(IPointer? p)+ {+ if (!_drag) return;+ _drag = false;+ p?.Capture(null);+ GestureEnd?.Invoke();+ Paint();+ }+}++// The noise source's colour as a spectral tilt across 20 Hz … 20 kHz: flat for white, falling+// for pink and red. Read-only — the Colour knob sets it.+internal sealed class TwinNoiseView : TwinParamGraph+{+ public override void Render(DrawingContext ctx)+ {+ var r = new Rect(Bounds.Size);+ if (r.Width < 24 || r.Height < 16) return;+ NotaGraph.Window(ctx, r);+ double c = P("noisecolor"), y0 = 6, y1 = 6 + c * (r.Height - 14);+ ctx.DrawLine(NotaGraph.SecondaryPen(NotaPalette.VizInk, 1.2), new Point(4, y0), new Point(r.Width - 4, y1));+ NotaGraph.Axis(ctx, r, NotaGraph.Corner.BottomLeft, "20");+ NotaGraph.Axis(ctx, r, NotaGraph.Corner.BottomRight, "20k");+ }+}++// ---- the modulation matrix as a grid (Consort's patch matrix, specs/035 / 055) ------------+// Rows are sources, columns destinations, a cell is the route between them: its depth on the side+// being edited, with the other side's depth as a tick when the two differ. Drag a cell for the+// depth (an empty one gets a route, the same on both sides while that drag lasts); ⌥-click types+// it (−100…+100 %); double-click or the menu's Clear removes the route. A row or column name opens+// the list to put another source or destination there.+internal sealed class TwinPatchMatrix : Control, IValueEntryHost+{+ internal readonly record struct Cell(int Slot, int Src, int Dst, float Depth, float Other);++ private static readonly Typeface Mono = NotaFonts.Mono;+ private static readonly Typeface Sans = NotaFonts.Sans;+ private static readonly Typeface SansMedium = NotaFonts.SansMedium;+ private int[] _rows = Array.Empty<int>(), _cols = Array.Empty<int>();+ private IReadOnlyList<Cell> _cells = Array.Empty<Cell>();+ private const double HeadH = 16, RowHdrW = 72;+ private (int s, int d)? _drag; // the route being dragged, by source and destination (the grid may re-order under it)+ private double _dragY, _dragV;++ public Func<int, string> SourceName = _ => "";+ public Func<int, string> DestinationName = _ => "";+ public string Corner = "";+ public event Action<int, int, float>? DepthChanged; // (src, dst, depth −1..1) — creates the route when missing+ public event Action<int, int>? Removed;+ public event Action<int, int>? GestureBegin;+ public event Action<int, int>? GestureEnd;+ public event Action<bool, int>? HeaderClicked; // (isRow, index)++ public TwinPatchMatrix() { ClipToBounds = true; Cursor = new Cursor(StandardCursorType.Hand); ValueEntry.AttachHost(this); }++ public void Set(int[] rows, int[] cols, IReadOnlyList<Cell> cells) { _rows = rows; _cols = cols; _cells = cells; InvalidateVisual(); }++ private double RowH => _rows.Length == 0 ? 0 : (Bounds.Height - HeadH) / _rows.Length;+ private double ColW => _cols.Length == 0 ? 0 : (Bounds.Width - RowHdrW) / _cols.Length;+ private Cell? Find(int s, int d) { foreach (var c in _cells) if (c.Src == s && c.Dst == d) return c; return null; }++ // ---- typed entry ------------------------------------------------------------+ private readonly Dictionary<(int s, int d), ValueField> _fields = new();+ private ValueField FieldOf(int s, int d) => _fields.TryGetValue((s, d), out var f) ? f : _fields[(s, d)] =+ new ValueField($"{SourceName(s)} → {DestinationName(d)}", () => ((Find(s, d)?.Depth ?? 0) + 1) / 2,+ n => NotaNum.F($"{(n * 2 - 1) * 100:+0;−0;0}\u2009%"),+ n => DepthChanged?.Invoke(s, d, (float)Math.Round((Math.Clamp(n, 0, 1) * 2 - 1) * 100) / 100f),+ () => GestureBegin?.Invoke(s, d), () => GestureEnd?.Invoke(s, d))+ {+ Clear = () => { if (Find(s, d) != null) Removed?.Invoke(s, d); },+ After = InvalidateVisual,+ };++ private (int r, int c) CellAt(Point p)+ {+ if (p.X < RowHdrW || p.Y < HeadH || RowH <= 0 || ColW <= 0) return (-1, -1);+ int r = (int)((p.Y - HeadH) / RowH), c = (int)((p.X - RowHdrW) / ColW);+ return r < _rows.Length && c < _cols.Length ? (r, c) : (-1, -1);+ }+ public IReadOnlyList<ValueField>? FieldsAt(Point p)+ => CellAt(p) is var (r, c) && r >= 0 && Find(_rows[r], _cols[c]) != null ? [FieldOf(_rows[r], _cols[c])] : null;+ public Rect AnchorOf(ValueField field)+ {+ for (int r = 0; r < _rows.Length; r++)+ for (int c = 0; c < _cols.Length; c++)+ if (_fields.TryGetValue((_rows[r], _cols[c]), out var f) && ReferenceEquals(f, field))+ return new Rect(RowHdrW + c * ColW + 2, HeadH + r * RowH + 2, ColW - 4, RowH - 4);+ return default;+ }+ public IReadOnlyList<ValueField> AllFields+ {+ get+ {+ var list = new List<ValueField>();+ for (int r = 0; r < _rows.Length; r++)+ for (int c = 0; c < _cols.Length; c++)+ if (Find(_rows[r], _cols[c]) != null) list.Add(FieldOf(_rows[r], _cols[c]));+ return list;+ }+ }++ protected override void OnPointerPressed(PointerPressedEventArgs e)+ {+ base.OnPointerPressed(e);+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed || e.ClickCount > 1) return;+ var p = e.GetPosition(this);+ if (p.Y < HeadH && p.X >= RowHdrW)+ {+ int c = (int)((p.X - RowHdrW) / ColW);+ if (c >= 0 && c < _cols.Length) HeaderClicked?.Invoke(false, c);+ e.Handled = true;+ return;+ }+ if (p.X < RowHdrW && p.Y >= HeadH)+ {+ int r = (int)((p.Y - HeadH) / RowH);+ if (r >= 0 && r < _rows.Length) HeaderClicked?.Invoke(true, r);+ e.Handled = true;+ return;+ }+ var (ri, ci) = CellAt(p);+ if (ri < 0) return;+ int s = _rows[ri], d = _cols[ci];+ var cur = Find(s, d);+ _drag = (s, d); _dragY = p.Y; _dragV = cur?.Depth ?? 0.5;+ GestureBegin?.Invoke(s, d);+ if (cur == null) DepthChanged?.Invoke(s, d, 0.5f);+ e.Pointer.Capture(this);+ e.Handled = true;+ }+ protected override void OnPointerMoved(PointerEventArgs e)+ {+ base.OnPointerMoved(e);+ if (_drag is not { } dg) return;+ double y = e.GetPosition(this).Y;+ bool fine = (e.KeyModifiers & (KeyModifiers.Control | KeyModifiers.Meta | KeyModifiers.Shift)) != 0;+ _dragV = Math.Clamp(_dragV + (_dragY - y) / (fine ? 1000.0 : 100.0), -1, 1);+ _dragY = y;+ DepthChanged?.Invoke(dg.s, dg.d, (float)Math.Round(_dragV * 100) / 100f);+ }+ protected override void OnPointerReleased(PointerReleasedEventArgs e)+ {+ base.OnPointerReleased(e);+ if (_drag is not { } dg) return;+ GestureEnd?.Invoke(dg.s, dg.d);+ _drag = null;+ InvalidateVisual();+ e.Pointer.Capture(null);+ }+ protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e)+ {+ if (_drag is { } dg) { GestureEnd?.Invoke(dg.s, dg.d); _drag = null; InvalidateVisual(); }+ base.OnPointerCaptureLost(e);+ }++ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width, h = Bounds.Height;+ if (w < 40 || h < 30 || _rows.Length == 0 || _cols.Length == 0) return;+ ctx.FillRectangle(Brushes.Transparent, new Rect(0, 0, w, h));+ double rh = RowH, cw = ColW;+ var corner = new FormattedText(Corner, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, SansMedium, NotaType.KnobLabel, NotaPalette.TextFaint);+ ctx.DrawText(corner, new Point(2, (HeadH - corner.Height) / 2));+ for (int c = 0; c < _cols.Length; c++)+ {+ var t = new FormattedText(DestinationName(_cols[c]), CultureInfo.InvariantCulture, FlowDirection.LeftToRight, SansMedium, NotaType.KnobLabel, NotaPalette.TextSecondary)+ { MaxTextWidth = cw - 4, MaxLineCount = 1, Trimming = TextTrimming.CharacterEllipsis };+ ctx.DrawText(t, new Point(RowHdrW + c * cw + (cw - t.Width) / 2, (HeadH - t.Height) / 2));+ }+ var rule = new Pen(NotaPalette.Rule, 1);+ var accent = NotaPalette.AccentColor;+ var fill = new SolidColorBrush(Color.FromArgb(0x30, accent.R, accent.G, accent.B));+ var edge = new Pen(NotaPalette.Accent, 1);+ var bar = new SolidColorBrush(Color.FromArgb(0x70, accent.R, accent.G, accent.B));+ var tick = new Pen(NotaPalette.TextSecondary, 1);+ for (int r = 0; r < _rows.Length; r++)+ {+ double y = HeadH + r * rh;+ ctx.DrawLine(rule, new Point(0, Math.Round(y) + 0.5), new Point(w, Math.Round(y) + 0.5));+ var t = new FormattedText(SourceName(_rows[r]), CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Sans, NotaType.RowLabel, NotaPalette.TextPrimary)+ { MaxTextWidth = RowHdrW - 6, MaxLineCount = 1, Trimming = TextTrimming.CharacterEllipsis };+ ctx.DrawText(t, new Point(2, y + (rh - t.Height) / 2));+ for (int c = 0; c < _cols.Length; c++)+ {+ var cell = new Rect(RowHdrW + c * cw + 2, y + 2, cw - 4, rh - 4);+ if (Find(_rows[r], _cols[c]) is { } cb)+ {+ ctx.DrawRectangle(fill, edge, cell, 2, 2);+ double mid = cell.X + cell.Width / 2, half = cell.Width / 2 - 2;+ double bw = half * Math.Abs(cb.Depth);+ ctx.FillRectangle(bar, new Rect(cb.Depth >= 0 ? mid : mid - bw, cell.Bottom - 3, bw, 2));+ if (Math.Abs(cb.Other - cb.Depth) > 1e-3)+ {+ double ox = Math.Round(mid + half * cb.Other) + 0.5;+ ctx.DrawLine(tick, new Point(ox, cell.Bottom - 5), new Point(ox, cell.Bottom - 1));+ }+ var v = new FormattedText($"{cb.Depth * 100:+0;−0;0}", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, NotaType.KnobValue, NotaPalette.TextPrimary);+ ctx.DrawText(v, new Point(cell.X + (cell.Width - v.Width) / 2, cell.Y + (cell.Height - 3 - v.Height) / 2));+ }+ else+ {+ ctx.DrawRectangle(NotaPalette.BgSunken, null, cell, 2, 2);+ var v = new FormattedText("·", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, NotaType.KnobValue, NotaPalette.TextFaint);+ ctx.DrawText(v, new Point(cell.X + (cell.Width - v.Width) / 2, cell.Y + (cell.Height - v.Height) / 2));+ }+ }+ }+ }+}diff --git a/src/managed/Nota.App/DeviceCardKit.cs b/src/managed/Nota.App/DeviceCardKit.csindex dd20a9b0..77797e1b 100644--- a/src/managed/Nota.App/DeviceCardKit.cs+++ b/src/managed/Nota.App/DeviceCardKit.cs@@ -202,10 +202,11 @@ internal static class DeviceCardKitinternal static Grid SliderRow(string label, Func<double> norm, Action<double> setNorm, Func<string> text, out Action sync,Action? begin = null, Action? end = null, Action? reset = null, bool bipolar = false, Func<bool>? dim = null,double labelWidth = 0, double trackWidth = double.NaN, double valueWidth = 42, bool modulation = false,- Func<double, string>? textAt = null)+ Func<double, string>? textAt = null, Action<SliderTrack>? withTrack = null){Action repaint = () => { };var track = new SliderTrack { Bipolar = bipolar, Modulation = modulation, Reset = reset is null ? null : () => { reset(); repaint(); } };+ withTrack?.Invoke(track);if (!double.IsNaN(trackWidth)) track.Width = trackWidth;var val = new TextBlock{@@ -262,6 +263,32 @@ internal static class DeviceCardKitreturn g;}+ // Words under a slider's track: the ends of a balance ("multi … ladder") or the marks of a+ // continuous choice ("LP · BP · HP · notch"), spread evenly — first left, last right. Put it+ // under a SliderRow; `left` / `right` are the row's label and value columns (plus their+ // spacing) so the words sit under the track only.+ internal static Control SliderMarks(string[] marks, double left = 0, double right = 0)+ {+ // N marks over N − 1 equal columns: a middle mark spans the two columns it divides and+ // centres on their boundary, so mark i sits at i / (N − 1) of the track.+ var g = new Grid { Margin = new Thickness(left, 1, right, 0) };+ int n = marks.Length, cols = Math.Max(1, n - 1);+ for (int c = 0; c < cols; c++) g.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));+ for (int i = 0; i < n; i++)+ {+ bool first = i == 0, last = i == n - 1 && n > 1;+ var tb = new TextBlock+ {+ Text = marks[i], FontSize = NotaType.KnobLabel, Foreground = TextTertiary,+ HorizontalAlignment = first ? HorizontalAlignment.Left : last ? HorizontalAlignment.Right : HorizontalAlignment.Center,+ };+ Grid.SetColumn(tb, first ? 0 : last ? cols - 1 : i - 1);+ if (!first && !last) Grid.SetColumnSpan(tb, 2);+ g.Children.Add(tb);+ }+ return g;+ }+/// <summary>A card section: no fill, no frame, a 1px Rule on the edges it shares with a/// neighbouring section (found from the layout unless <paramref name="edges"/> names/// them). Content keeps the 1px inset of the framed box it replaces. Graph windows anddiff --git a/src/managed/Nota.App/DeviceCards/InstrumentCardFactory.cs b/src/managed/Nota.App/DeviceCards/InstrumentCardFactory.csindex 8652060d..571df04b 100644--- a/src/managed/Nota.App/DeviceCards/InstrumentCardFactory.cs+++ b/src/managed/Nota.App/DeviceCards/InstrumentCardFactory.cs@@ -30,6 +30,7 @@ internal sealed class InstrumentCardFactory[15] = new ConsortInstrumentCard(),[16] = new KeysInstrumentCard(),[17] = new MosaicInstrumentCard(),+ [18] = new TwinInstrumentCard(),};/// <summary>Resolve the editor for a built-in instrument kind. The Sampler (1) alwaysdiff --git a/src/managed/Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs b/src/managed/Nota.App/DeviceCards/Instruments/TwinInstrumentCard.csnew file mode 100644index 00000000..113d24a8--- /dev/null+++ b/src/managed/Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs@@ -0,0 +1,1199 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Detail · Devices — built-in Nota Twin editor (instrument kind 18, specs/055), first cut (US1):+// the voice of one part in a 700 × 260 card.+//+// Morph 64 the part's Morph — on screen on every tab, it is what the instrument is about.+// Centre eight tabs, each a signal chain of islands:+// Osc — Osc 1 ▸ Osc 2 ▸ Noise: wave (triangle → saw → square), width, Metal,+// tuning, level and the balance between the two filters; Osc 2's sync,+// FM into Osc 1 and into the multimode cutoff, low-frequency mode.+// Filter — Multimode ▸ Route ▸ Ladder, with Brute feedback and drive in between.+// Env — filter, amp and mod envelopes.+// LFO — three LFOs (one at a time) and the vibrato depth (LFO 1, by the mod wheel).+// Matrix — the routes (up to 64: source → destination, a depth per side, so the+// depth morphs too) and the part's eight macros, which are sources.+// FX — the part's effects: Mod FX (chorus / flanger / phaser / ensemble) ▸ Delay+// (free or synced, ping-pong) ▸ Reverb, each switchable, all of it morphing;+// the section's own switch bypasses it for Nota's effect devices.+// Seq — the sequencer (a pattern of steps on a grid of sixteen: notes, velocity,+// gate or tie; pattern, length, rate, swing, transpose / latch, step record,+// motion lanes, "To clip") or the arpeggiator (mode, octaves, gate, hold).+// Voice — the voice mode, the voice cap, glide, unison detune, stereo spread,+// drift, bend range, the part's volume and pan, and the expression pad (X → the+// multimode cutoff, Y → the morph, Z → vibrato depth, until the matrix routes them).+//+// The A / B switch under Morph picks the side every knob edits (and so the side automation and+// MIDI learn write to, FR-024); each knob also ticks the other side's value outside its groove+// and, while the morph sits between, dots where the sound is now. A→B, B→A and Swap rewrite a+// side in one undo step. Single / Layer / Split and the Lower / Upper switch sit at the right of+// the tab row (US9): every tab edits the part chosen there; Voice → Part sets the split key+// (learnable from a played key), the voice share and the part's octave, and its Parts menu+// copies, swaps or loads the parts.+// Layout (specs/055/design): sections butt on rules with no chevrons between them, and the+// sections of a tab keep one row order — header, graph or chooser, knob rows, slider rows — so+// their knob rows share a baseline. There is no status line: the header badge and the side+// switch already say it. Neutral ink is the parameter; teal marks modulation amounts; the+// accent only what is live or chosen; an effect that is off greys its body (Inactive).+// Everything is a plugin param, so the card follows automation live.++using System;+using System.Collections.Generic;+using System.Linq;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using Avalonia.Layout;+using Avalonia.Media;+using Nota.Application;+using Nota.Application.Localization;+using static Nota.App.DeviceCardKit;++namespace Nota.App;++internal sealed class TwinInstrumentCard : IInstrumentCard+{+ public bool BodyOnly => true;+ public string Subtitle => "Morphing poly";+ public double CardWidth => 700;++ private const double MorphW = 70, TabH = 22;+ // The side each track's card edits (0 = A, 1 = B), its part (0 = Lower, 1 = Upper) and its+ // open tab: editor state, kept across rebuilds (the side and part switches rebuild the card).+ private static readonly Dictionary<int, int> EditSides = new();+ private static readonly Dictionary<int, int> EditParts = new();+ private static readonly Dictionary<int, int> OpenTabs = new();+ // The matrix grid's rows and columns last picked, per track and part (most recent first).+ private static readonly Dictionary<(int, string), List<int>> MatrixRowPrefs = new();+ private static readonly Dictionary<(int, string), List<int>> MatrixColPrefs = new();+ // LFO 1, LFO 2, Mod env, Velocity, Mod wheel, Pressure, Pad X (TwinMatrix.Sources indices).+ private static readonly int[] DefaultMatrixRows = { 1, 2, 6, 7, 13, 10, 15 };+ private static IEnumerable<int> DefaultMatrixCols(IAudioEngine e, int track) => new[]+ {+ 1, // Morph+ Nota.Application.Twin.TwinMatrix.DestinationOfSide("ldcut"), Nota.Application.Twin.TwinMatrix.DestinationOfSide("mmcut"),+ 2, // Pitch+ Nota.Application.Twin.TwinMatrix.DestinationOfSide("o1wave"), 5, // Vibrato+ };++ private static readonly string[] TabNames = { "Osc", "Filter", "Env", "LFO", "Matrix", "FX", "Seq", "Voice" };+ private static readonly string[] SeqRates = { "1/4", "1/8", "1/8T", "1/16", "1/16T", "1/32" };+ private static readonly string[] ArpModes = { "Up", "Down", "Up/down", "Random", "As played", "Chord" };+ private static readonly int[] SeqLengths = { 4, 8, 12, 16, 24, 32, 48, 64 };+ private static readonly string[] ModFxTypes = { "Chorus", "Flanger", "Phaser", "Ensemble" };+ private static readonly string[] DelayDivs = { "1/16", "1/8T", "1/8", "1/8.", "1/4T", "1/4", "1/4.", "1/2" };+ private static readonly string[] VoiceModes = { "Poly", "Mono", "Legato", "Unison" };+ private static readonly string[] Layouts = { "Single", "Layer", "Split" };+ private static readonly string[] PartNames = { "Lower", "Upper" };+ private static readonly string[] SeqTargets = { "Lower", "Upper", "Both" };+ private static readonly string[] Slopes = { "12", "24" };+ private static readonly string[] LfoShapes = { "Sine", "Tri", "Saw", "Square", "S&H", "Smooth" };+ private static readonly string[] LfoModes = { "Voice", "Global" };+ private static readonly string[] SpreadModes = { "Voice", "Key", "Unison" };+ private static readonly string[] SyncNames = { "8 bars", "4 bars", "2 bars", "1 bar", "1/2", "1/4.", "1/4", "1/8.", "1/4T", "1/8", "1/8T", "1/16", "1/16T", "1/32" };++ // The engine's own maps (TwinVoice.h), so a readout says what it does.+ private static double ExpMap(float v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0f, 1f));+ private static string Pct(float v) => NotaNum.Pct(v);+ private static string Bip(float v) => NotaNum.Unit((v - 0.5f) * 200, "+0;−0;0", "%");+ private static string Cutoff(float v) => NotaNum.Hz(20 * Math.Pow(1000, Math.Clamp(v, 0f, 1f)));+ private static string EnvOct(float v) => NotaNum.Unit((v - 0.5f) * 16, "+0.0;−0.0;0", "oct");+ private static string Coarse(float v) => NotaNum.Unit(Math.Clamp(Math.Round(v * 48), 0, 48) - 24, "+0;−0;0", "st");+ private static string Fine(float v) => NotaNum.Unit(Math.Round((v - 0.5f) * 100), "+0;−0;0", "c");+ private static string Attack(float v) => NotaNum.Time(ExpMap(v, 0.0005, 10));+ private static string Decay(float v) => NotaNum.Time(ExpMap(v, 0.003, 15));+ private static string Delay(float v) => v < 0.002f ? "off" : NotaNum.Time(ExpMap(v, 0.001, 5));+ private static string Glide(float v) => v < 0.002f ? "off" : NotaNum.Time(ExpMap(v, 0.005, 5));+ private static string Fade(float v) => v < 0.002f ? "off" : NotaNum.Time(ExpMap(v, 0.01, 10));+ private static string LfoRate(float v)+ {+ double hz = ExpMap(v, 0.02, 40);+ return hz >= 9.995 ? NotaNum.Hz(hz) : NotaNum.Unit(hz, hz < 0.995 ? "0.00" : "0.0", "Hz");+ }+ private static string Wave(float v) => v <= 0.02f ? "tri" : v < 0.48f ? "tri–saw" : v <= 0.52f ? "saw" : v < 0.98f ? "saw–sqr" : "square";+ private static string Width(float v) => NotaNum.Pct(0.05f + 0.9f * v);+ private static string Semis(float v) => NotaNum.Unit(v, "0.00", "st");+ private static string Detune(float v) => NotaNum.Unit(Math.Round(v * 50), "±0", "c");+ private static string Voices(float v) => (4 + Math.Clamp((int)Math.Round(v * 8), 0, 8)).ToString(NotaNum.Culture);+ private static int LowerShare(float share, int cap) => Math.Clamp(2 + 2 * Math.Clamp((int)Math.Round(share * 4), 0, 4), 2, cap - 2);+ private static string SplitKey(float v) => NoteName(Math.Clamp((int)Math.Round(v * 127), 0, 127));+ private static string Octave(float v) => NotaNum.Unit(Math.Clamp((int)Math.Round(v * 4), 0, 4) - 2, "+0;−0;0", "oct");+ private static string PanText(float v)+ {+ double p = (v - 0.5) * 200;+ return Math.Abs(p) < 0.5 ? "C" : (p < 0 ? "L" : "R") + NotaNum.Str(Math.Abs(p), "0");+ }++ // Two sizes (the instrument's "view" param, InstrumentView): L — every tab — and S, the+ // performance view: Morph and the side switch, the pad, and four sound knobs.+ public double WidthFor(IAudioEngine engine, int trackId) => InstrumentView.IsMini(engine, trackId) ? 260 : CardWidth;+ public Control? HeaderAccessory(DeviceCardContext ctx)+ => MidiCardHeader.SizeToggle(ctx, () => InstrumentView.IsMini(ctx.Engine, ctx.TrackId), m => InstrumentView.SetMini(ctx.Engine, ctx.TrackId, m));++ public string? VoiceLabel(IAudioEngine engine, int trackId, int active)+ {+ int n = engine.PluginParamCount(trackId, -1);+ for (int i = 0; i < n; i++)+ if (engine.PluginParamId(trackId, -1, i) == "voices")+ return $"{active}/{Voices(engine.PluginParamGet(trackId, -1, i))}";+ return null;+ }++ public Control Build(DeviceCardContext ctx)+ {+ var engine = ctx.Engine;+ int track = ctx.TrackId;+ int pc = engine.PluginParamCount(track, -1);+ var idx = new Dictionary<string, int>();+ for (int i = 0; i < pc; i++) idx[engine.PluginParamId(track, -1, i)] = i;+ int I(string id) => idx.TryGetValue(id, out var i) ? i : -1;+ float G(string id) => I(id) is var i and >= 0 ? engine.PluginParamGet(track, -1, i) : 0f;+ void SetP(string id, float v) { if (I(id) is var i and >= 0) engine.PluginParamSet(track, -1, i, Math.Clamp(v, 0f, 1f)); }+ void Begin(string id) { if (I(id) >= 0) engine.BeginAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id); }+ void End(string id) { if (I(id) >= 0) engine.EndAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id); }+ // A one-shot change (a switch, a segment, a reset): its own undo step and automation write.+ void Once(string id, float v) { Begin(id); SetP(id, v); End(id); }+ int Sel(string id, int n) => Math.Clamp((int)Math.Round(G(id) * (n - 1)), 0, n - 1);++ int sideIx = EditSides.TryGetValue(track, out var es) ? es : 0;+ int layout = Sel("mode", 3);+ int partIx = layout == 0 ? 0 : EditParts.TryGetValue(track, out var ep) ? ep : 0;+ string PartKey = partIx == 0 ? "lo" : "up", Part = PartKey + ".";+ string Side = Part + (sideIx == 0 ? "a." : "b."), Other = Part + (sideIx == 0 ? "b." : "a.");+ var readouts = new List<Action>();+ int tab = OpenTabs.TryGetValue(track, out var ot) ? ot : 0;+ Nota.Application.Twin.TwinPatterns.Pattern[]? pats = null; // the sequencer's patterns (Seq tab)+ // Inactive looks, applied after the readouts (a switch's repaint would undo them).+ var dims = new List<Action>();+ Action showTab = () => { };++ void Refresh()+ {+ foreach (var r in readouts) r();+ foreach (var d in dims) d();+ }+ void SetParam(string id, float v) { Once(id, v); Refresh(); }++ static TextBlock Cap(string t) => new()+ {+ Text = NotaText.Label(t), FontSize = NotaType.KnobLabel, FontWeight = FontWeight.Medium,+ Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center,+ };+ static TextBlock Title(string t) => new()+ {+ Text = NotaText.Label(t), FontSize = NotaType.DeviceSection, FontWeight = FontWeight.SemiBold,+ Foreground = NotaPalette.TextMuted, VerticalAlignment = VerticalAlignment.Center,+ };++ // A knob cell on a param id; the learn name is the param's full display name.+ // `rows`: a knob in a rebuilt route row follows through that row list instead of the+ // card's live-follow registry, so rebuilding the rows leaves nothing behind.+ Control PKnob(string id, string label, Func<float, string> fmt, double size = 34, double cellW = 46, IBrush? arc = null, List<Action>? rows = null)+ {+ if (!idx.TryGetValue(id, out var pi)) return new Panel();+ var value = new TextBlock { Text = fmt(G(id)), Foreground = TextPrimary };+ var knob = new Knob(G(id), 1.0)+ {+ Accent = true, ArcColor = arc, Default = engine.InstrumentParamDefault(track, pi),+ Width = size, Height = size,+ };+ knob.Format = v => fmt((float)v);+ knob.ValueChanged += v => { engine.PluginParamSet(track, -1, pi, (float)v); value.Text = fmt((float)v); Refresh(); };+ knob.GestureBegin += () => Begin(id);+ knob.GestureEnd += () => End(id);+ if (rows is null) ctx.AddInstFader(pi, knob, value, fmt);+ else rows.Add(() => { if (!knob.Dragging) { knob.Value = G(id); value.Text = fmt(G(id)); } });+ MidiLearn.Bind(knob, MidiTarget.PluginParam(track, -1, pi), engine.PluginParamName(track, -1, pi));+ if (id.StartsWith(Side, StringComparison.Ordinal) && I(Other + id[Side.Length..]) >= 0)+ {+ string oid = Other + id[Side.Length..];+ void Marks()+ {+ float own = G(id), other = G(oid), m = G(Part + "morph");+ float a = sideIx == 0 ? own : other, b = sideIx == 0 ? other : own;+ float sounding = a + (b - a) * m;+ knob.OtherValue = Math.Abs(other - own) > 1e-4f ? other : double.NaN;+ knob.SoundingValue = Math.Abs(sounding - own) > 2e-3f ? sounding : double.NaN;+ ToolTip.SetTip(knob, $"A {fmt(a)} · B {fmt(b)} · now {fmt(sounding)}");+ }+ (rows ?? readouts).Add(Marks);+ Marks();+ }+ return KnobCell(label, knob, value, cellW);+ }++ Control Chips(string id, string[] names, double padX = 6)+ {+ int n = names.Length;+ var seg = Segments(names, () => Sel(id, n), iv => SetParam(id, iv / (float)(n - 1)), out var sync, padX: padX);+ readouts.Add(sync);+ if (I(id) is var pi and >= 0) MidiLearn.Bind(seg, MidiTarget.PluginParam(track, -1, pi), engine.PluginParamName(track, -1, pi));+ return seg;+ }++ Control Toggle(string label, string id)+ {+ var host = Switch(label, () => G(id) >= 0.5f, () => SetParam(id, G(id) >= 0.5f ? 0f : 1f), out var sync);+ readouts.Add(sync);+ if (I(id) is var pi and >= 0) MidiLearn.Bind(host, MidiTarget.PluginParam(track, -1, pi), engine.PluginParamName(track, -1, pi));+ return host;+ }++ static StackPanel Row(params Control[] cells)+ {+ var p = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2, HorizontalAlignment = HorizontalAlignment.Center };+ foreach (var c in cells) p.Children.Add(c);+ return p;+ }++ // A section of a tab: title (and an optional control at its right) on a 16 px header row,+ // over rows. `w` fixes its width; 0 lets it take what the tab has left (the last one).+ Control Island(string title, Control? head, double w, params Control[] rows)+ {+ var header = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), Height = 16 };+ header.Children.Add(Title(title));+ if (head is not null) { head.VerticalAlignment = VerticalAlignment.Center; Grid.SetColumn(head, 1); header.Children.Add(head); }+ var stack = new StackPanel { Spacing = 4, Margin = new Thickness(8, 5, 8, 4) };+ stack.Children.Add(header);+ foreach (var r in rows) stack.Children.Add(r);+ var s = Section(stack);+ if (w > 0) s.Width = w;+ return s;+ }+ // A tab's sections side by side, butted on their rules; the last one fills.+ static DockPanel Chain(params Control[] islands)+ {+ var p = new DockPanel { LastChildFill = true };+ foreach (var c in islands) { DockPanel.SetDock(c, Dock.Left); p.Children.Add(c); }+ return p;+ }+ // A row that keeps a fixed height, so the rows after it line up across sections.+ static Control Fixed(double h, Control? c = null) => new Border { Height = h, Child = c, VerticalAlignment = VerticalAlignment.Top };++ // A slider row on a param, with words under its track (the ends of a balance, or the marks+ // of a continuous choice). `bare` drops the label and value columns: the marks say it.+ Control PSlider(string id, string label, Func<float, string> fmt, string[] marks, bool bare = false, double labelW = 38, double valueW = 34)+ {+ if (!idx.TryGetValue(id, out var pi)) return new Panel();+ float def = engine.InstrumentParamDefault(track, pi);+ var row = SliderRow(bare ? "" : label, () => G(id), v => { SetP(id, (float)v); Refresh(); }, () => bare ? "" : fmt(G(id)), out var sync,+ begin: () => Begin(id), end: () => End(id), reset: () => { Begin(id); SetP(id, def); End(id); Refresh(); },+ labelWidth: bare ? 0 : labelW, valueWidth: bare ? 0 : valueW);+ readouts.Add(sync);+ MidiLearn.Bind(row, MidiTarget.PluginParam(track, -1, pi), engine.PluginParamName(track, -1, pi));+ ToolTip.SetTip(row, label);+ return new StackPanel { Spacing = 0, Children = { row, SliderMarks(marks, bare ? 0 : labelW + 8, bare ? 8 : valueW + 8) } };+ }++ // A value well on a param (the ADSR times under an envelope graph), named under it.+ Control PWell(string id, string label, Func<float, string> fmt)+ {+ if (!idx.TryGetValue(id, out var pi)) return new Panel();+ var well = new TwinValueWell { Format = v => fmt((float)v), Default = engine.InstrumentParamDefault(track, pi) };+ well.Value = G(id);+ well.ValueChanged += v => { SetP(id, (float)v); Refresh(); };+ well.GestureBegin += () => Begin(id);+ well.GestureEnd += () => End(id);+ readouts.Add(() => { if (!well.Dragging) well.Value = G(id); });+ MidiLearn.Bind(well, MidiTarget.PluginParam(track, -1, pi), engine.PluginParamName(track, -1, pi));+ ValueEntry.Attach(well, ValueEntry.Probing(label, () => G(id), v => { SetP(id, (float)v); Refresh(); }, () => fmt(G(id)),+ () => Begin(id), () => End(id), reset: () => SetParam(id, (float)well.Default)), well.Readout);+ var name = new TextBlock+ {+ Text = NotaText.Label(label), FontSize = NotaType.KnobLabel, FontWeight = FontWeight.Medium, Foreground = TextSecondary,+ HorizontalAlignment = HorizontalAlignment.Center, LineHeight = 10,+ };+ return new StackPanel { Spacing = 1, Children = { well, name } };+ }++ // A hint line inside a section (Ink 3, 8 px).+ static TextBlock Note(string t) => new()+ {+ Text = t, FontSize = NotaType.KnobLabel, Foreground = TextTertiary, TextWrapping = TextWrapping.Wrap, LineHeight = 11,+ };++ // A section body that goes inactive while `off` holds (the effect is switched off, the+ // param does nothing in this mode); it stays editable.+ T DimWhen<T>(T c, Func<bool> off) where T : Control+ {+ bool last = false;+ dims.Add(() => { bool o = off(); if (o || last) Inactive.Set(c, o, interactive: true); last = o; });+ return c;+ }++ string S(string id) => Side + id;+ // A graph bound to the side being edited; it redraws with the card's readouts.+ T Graph<T>(T g, double w, double h) where T : TwinParamGraph+ {+ g.Width = w; g.Height = h;+ g.Get = G; g.Set = (id, v) => { SetP(id, v); Refresh(); }; g.Begin = Begin; g.End = End;+ g.Bind(Side);+ readouts.Add(g.Refresh);+ return g;+ }+ static string Bal(float v) => v <= 0.005f ? "multi" : v >= 0.995f ? "ladder" : NotaNum.Pct(v);+ // ---- Osc tab ------------------------------------------------------------+ // Each source: its wave over the full width (drag sideways for Wave), two knob rows, and+ // the balance between the two filters as a slider with its ends named.+ string[] FilterEnds = { "multi", "ladder" };+ Control Osc(int n)+ {+ string o = $"o{n}";+ var top = Row(PKnob(S(o + "wave"), "Wave", Wave), PKnob(S(o + "pw"), "Width", Width),+ PKnob(S(o + "metal"), "Metal", Pct), PKnob(S(o + "level"), "Level", Pct));+ var tune = n == 1+ ? Row(PKnob(S(o + "coarse"), "Coarse", Coarse), PKnob(S(o + "fine"), "Fine", Fine))+ : Row(PKnob(S(o + "coarse"), "Coarse", Coarse), PKnob(S(o + "fine"), "Fine", Fine),+ PKnob(S("fm21"), "FM 1", Pct, arc: Teal), PKnob(S("fmfilt"), "FM cut", Pct, arc: Teal));+ tune.HorizontalAlignment = HorizontalAlignment.Left;+ var head = n == 1 ? null : new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, Children = { Toggle("Sync", S("sync")), Toggle("Low", S("o2lo")) } };+ return Island($"Osc {n}", head, 212, Graph(new TwinWaveView(n), 196, 34), top, Fixed(53, tune), PSlider(S(o + "bal"), "To filter", Bal, FilterEnds));+ }+ var noiseKnobs = Row(PKnob(S("noiselevel"), "Level", Pct), PKnob(S("noisecolor"), "Colour", v => v < 0.2f ? "white" : v < 0.6f ? "pink" : "red"));+ noiseKnobs.HorizontalAlignment = HorizontalAlignment.Left;+ var oscBody = Chain(Osc(1), Osc(2),+ Island("Noise", null, 0, Graph(new TwinNoiseView(), 166, 34), noiseKnobs, Fixed(53), PSlider(S("noisebal"), "To filter", Bal, FilterEnds)));++ // ---- Filter tab ---------------------------------------------------------+ // Mode and Route are continuous (they morph), so they are sliders whose marks name the+ // regions; the route draws itself under its slider.+ const double CutW = 64;+ var filterBody = Chain(+ Island("Multimode", null, 144,+ Fixed(24, PSlider(S("mmmode"), "Mode", v => v < 0.17f ? "LP" : v < 0.5f ? "BP" : v < 0.83f ? "HP" : "notch", new[] { "LP", "BP", "HP", "notch" }, bare: true)),+ Row(PKnob(S("mmcut"), "Cutoff", Cutoff, 44, CutW), PKnob(S("mmres"), "Resonance", Pct, 44, CutW)),+ Row(PKnob(S("mmkey"), "Key", Pct, cellW: CutW, arc: Teal), PKnob(S("mmenv"), "Env", EnvOct, cellW: CutW, arc: Teal))),+ Island("Route", null, 132,+ Fixed(24, PSlider(S("route"), "Route", v => v <= 0.01f ? "series" : v >= 0.99f ? "parallel" : Pct(v), new[] { "series", "parallel" }, bare: true)),+ Graph(new TwinRouteView(), 116, 62),+ Row(PKnob(S("brute"), "Brute", Pct, cellW: 58), PKnob(S("drive"), "Drive", Pct, cellW: 58))),+ Island("Ladder", Chips(S("ldslope"), Slopes), 144,+ Fixed(24, Note(Loc.T("device.twin.slope_in_db_per_octave"))),+ Row(PKnob(S("ldcut"), "Cutoff", Cutoff, 44, CutW), PKnob(S("ldres"), "Resonance", Pct, 44, CutW)),+ Row(PKnob(S("ldkey"), "Key", Pct, cellW: CutW, arc: Teal), PKnob(S("ldenv"), "Env", EnvOct, cellW: CutW, arc: Teal))),+ Island("Response", null, 0, Graph(new TwinFilterView(), 172, 172)));++ // ---- Env tab ------------------------------------------------------------+ // An envelope: drag its handles on the graph (attack · decay and sustain · release), or the+ // four named times under it; the knobs keep velocity and the curve (delay for the mod env).+ Control Env(string title, string e, bool mod, double w)+ {+ var times = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*,*"), ColumnSpacing = 3 };+ var cells = new[] { PWell(S(e + "a"), "Attack", Attack), PWell(S(e + "d"), "Decay", Decay), PWell(S(e + "s"), "Sustain", Pct), PWell(S(e + "r"), "Release", Decay) };+ for (int k = 0; k < 4; k++) { Grid.SetColumn(cells[k], k); times.Children.Add(cells[k]); }+ var knobs = mod+ ? Row(PKnob(S(e + "dly"), "Delay", Delay, cellW: 58), PKnob(S(e + "vel"), "Velocity", Pct, cellW: 58, arc: Teal))+ : Row(PKnob(S(e + "vel"), "Velocity", Pct, cellW: 58, arc: Teal), PKnob(S(e + "curve"), "Curve", Pct, cellW: 58));+ return Island(title, mod ? Toggle("Loop", S("menvloop")) : null, w, Graph(new TwinEnvView(e, mod), 186, 70), times, knobs);+ }+ var envBody = Chain(Env("Filter env", "fenv", false, 204), Env("Amp env", "aenv", false, 204), Env("Mod env", "menv", true, 0));++ // ---- LFO tab ------------------------------------------------------------+ // One LFO at a time (the picker in the header): shape, switches, then rate, fade and amount+ // as main knobs beside a large graph with the live phase.+ int lfoSel = 0;+ var lfoGraphs = new TwinLfoView[3];+ Control Lfo(int n)+ {+ string l = $"lfo{n}";+ double ks = n == 3 ? 34 : 44, kw = n == 3 ? 44 : 64;+ var rateCell = PKnob(S(l + "rate"), "Rate", LfoRate, ks, kw);+ var divCell = PKnob(S(l + "div"), "Division", v => SyncNames[Math.Clamp((int)Math.Round(v * 13), 0, 13)], ks, kw);+ readouts.Add(() => { bool sync = G(S(l + "sync")) >= 0.5f; rateCell.IsVisible = !sync; divCell.IsVisible = sync; });+ var switches = new DockPanel { LastChildFill = false };+ var sw = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children = { Toggle("Sync", S(l + "sync")), Toggle("Retrig", S(l + "retrig")) } };+ var mode = Chips(S(l + "mode"), LfoModes, 5);+ DockPanel.SetDock(sw, Dock.Left); DockPanel.SetDock(mode, Dock.Right);+ switches.Children.Add(sw); switches.Children.Add(mode);+ var shapes = Segments(LfoShapes, () => Sel(S(l + "shape"), 6), iv => SetParam(S(l + "shape"), iv / 5f), out var shapeSync, fill: true, padX: 2);+ readouts.Add(shapeSync);+ if (I(S(l + "shape")) is var si and >= 0) MidiLearn.Bind(shapes, MidiTarget.PluginParam(track, -1, si), engine.PluginParamName(track, -1, si));+ var knobs = n == 3+ ? Row(rateCell, divCell, PKnob(S(l + "fade"), "Fade", Fade, cellW: kw), PKnob(S(l + "amt"), "Amount", Pct, cellW: kw, arc: Teal),+ PKnob(S("lfo3sym"), "Symmetry", Pct, cellW: kw), PKnob(S("lfo3curve"), "Curve", Bip, cellW: kw))+ : Row(rateCell, divCell, PKnob(S(l + "fade"), "Fade", Fade, ks, kw), PKnob(S(l + "amt"), "Amount", Pct, ks, kw, Teal));+ knobs.HorizontalAlignment = HorizontalAlignment.Left;+ var body = new StackPanel { Spacing = 6, Width = 232, Children = { shapes, switches, knobs } };+ var shape = Graph(new TwinLfoView(n), 240, 166);+ lfoGraphs[n - 1] = shape;+ var page = new DockPanel { LastChildFill = true };+ DockPanel.SetDock(body, Dock.Left); page.Children.Add(body);+ shape.HorizontalAlignment = HorizontalAlignment.Right;+ page.Children.Add(shape);+ return page;+ }+ var lfoPages = new Control[] { Lfo(1), Lfo(2), Lfo(3) };+ var lfoPick = Segments(new[] { "LFO 1", "LFO 2", "LFO 3" }, () => lfoSel, iv =>+ {+ lfoSel = iv;+ for (int k = 0; k < lfoPages.Length; k++) lfoPages[k].IsVisible = k == lfoSel;+ Refresh();+ }, out var lfoPickSync, padX: 5);+ readouts.Add(lfoPickSync);+ var lfoHost = new Panel();+ foreach (var pg in lfoPages) lfoHost.Children.Add(pg);+ for (int k = 1; k < lfoPages.Length; k++) lfoPages[k].IsVisible = false;+ var vibNote = Note("LFO 1 × mod wheel");+ vibNote.HorizontalAlignment = HorizontalAlignment.Center;+ var lfoBody = Chain(Island("LFO", lfoPick, 500, lfoHost),+ Island("Vibrato", null, 0, Row(PKnob(S("vibamt"), "Depth", Semis, 44, 80, Teal)), vibNote));++ // ---- the tab strip ----------------------------------------------------+ // ---- expression pad -----------------------------------------------------+ Control PadView(double size = 104, bool legend = true, double width = 0)+ {+ var pad = new TwinExpressionPad { Width = width > 0 ? width : size + 8, Height = size };+ pad.XyChanged = (x, y) => { SetP("padx", (float)x); SetP("pady", (float)y); Refresh(); };+ pad.ZChanged = z => { SetP("padz", (float)z); Refresh(); };+ pad.GestureBegin = () => { Begin("padx"); Begin("pady"); Begin("padz"); };+ pad.GestureEnd = () => { End("padx"); End("pady"); End("padz"); };+ pad.Reset = () => { engine.BeginUndoGroup(); Once("padx", 0.5f); Once("pady", 0.5f); engine.EndUndoGroup(); Refresh(); };+ readouts.Add(() => pad.SetValues(G("padx"), G("pady"), G("padz")));+ if (I("padx") is var pi and >= 0) MidiLearn.Bind(pad, MidiTarget.PluginParam(track, -1, pi), "Pad X");+ var legendText = new TextBlock { FontSize = NotaType.KnobValue, FontFamily = NotaFonts.MonoFamily, Foreground = TextSecondary, HorizontalAlignment = HorizontalAlignment.Center };+ readouts.Add(() => legendText.Text = $"X {Bip(G("padx"))} · Y {Bip(G("pady"))} · Z {Pct(G("padz"))}");+ ToolTip.SetTip(pad, Loc.T("device.twin.pad_hint"));+ return legend ? new StackPanel { Spacing = 3, Children = { pad, legendText } } : pad;+ }++ // ---- Matrix tab ---------------------------------------------------------+ // A source × destination grid, as Consort's patch matrix: drag a cell for the depth on the+ // side being edited (an empty cell gets a route), double-click removes it, a row or column+ // name puts another source or destination there. Rows and columns show the routes first,+ // then the ones last picked (kept per track and part across rebuilds).+ string sideKey = sideIx == 0 ? "a" : "b", otherKey = sideIx == 0 ? "b" : "a";+ void ShowSources(Control at, Action<int> pick)+ {+ var f = new MenuFlyout();+ for (int k = 1; k < Nota.Application.Twin.TwinMatrix.Sources.Length; k++)+ {+ int kv = k;+ var mi = new MenuItem { Header = Nota.Application.Twin.TwinMatrix.Sources[k] };+ mi.Click += (_, _) => pick(kv);+ f.Items.Add(mi);+ }+ f.ShowAt(at);+ }+ void ShowDestinations(Control at, Action<int> pick)+ {+ var f = new MenuFlyout();+ var groups = new Dictionary<string, MenuItem>();+ for (int k = 1; k < Nota.Application.Twin.TwinMatrix.DestinationCount; k++)+ {+ int kv = k;+ string name = Nota.Application.Twin.TwinMatrix.DestinationName(engine, track, k);+ string grp = Nota.Application.Twin.TwinMatrix.DestinationGroup(engine, track, k);+ var mi = new MenuItem { Header = grp.Length > 0 ? name[(grp.Length + 1)..] : name };+ mi.Click += (_, _) => pick(kv);+ if (grp.Length == 0) { f.Items.Add(mi); continue; }+ if (!groups.TryGetValue(grp, out var g)) { g = new MenuItem { Header = grp }; groups[grp] = g; f.Items.Add(g); }+ g.Items.Add(mi);+ }+ f.ShowAt(at);+ }+ // The rows and columns on show, kept per track and part across rebuilds: the user's picks+ // stay where they put them; a route whose source or destination isn't shown takes an empty+ // row / column (never the one just picked), and the grid grows to 8 × 6 before that.+ var prefKey = (track, PartKey);+ if (!MatrixRowPrefs.TryGetValue(prefKey, out var visRows)) MatrixRowPrefs[prefKey] = visRows = new List<int>();+ if (!MatrixColPrefs.TryGetValue(prefKey, out var visCols)) MatrixColPrefs[prefKey] = visCols = new List<int>();+ // The part's routes, read through the card's own param map (the tick reads them often).+ List<TwinPatchMatrix.Cell> Cells()+ {+ var l = new List<TwinPatchMatrix.Cell>();+ for (int r = 1; r <= Nota.Application.Twin.TwinMatrix.Slots; r++)+ {+ int src = (int)Math.Round(G($"{Part}m{r}.src") * Nota.Application.Twin.TwinMatrix.SrcScale);+ int dst = (int)Math.Round(G($"{Part}m{r}.dst") * Nota.Application.Twin.TwinMatrix.DstScale);+ if (src <= 0 || dst <= 0) continue;+ l.Add(new(r, src, dst, (G($"{Part}{sideKey}.m{r}amt") - 0.5f) * 2f, (G($"{Part}{otherKey}.m{r}amt") - 0.5f) * 2f));+ }+ return l;+ }+ const int GridRows = 6, GridCols = 5, MaxRows = 8, MaxCols = 6;+ int keepRow = -1, keepCol = -1; // the row / column the user picked last: auto-fill leaves it+ // Puts `k` on show: at `at` (a pick; swaps if it is shown elsewhere), or in the last row+ // without routes (never `keep`), or failing that the last row.+ static void Put(List<int> vis, int k, int at, int keep, ICollection<int> used)+ {+ int was = vis.IndexOf(k);+ if (at >= 0)+ {+ if (was >= 0) (vis[was], vis[at]) = (vis[at], vis[was]);+ else vis[at] = k;+ return;+ }+ if (was >= 0) return;+ for (int i = vis.Count - 1; i >= 0; i--)+ if (i != keep && !used.Contains(vis[i])) { vis[i] = k; return; }+ if (vis.Count > 0) vis[^1] = k;+ }+ static void Fit(List<int> vis, IEnumerable<int> usedSeq, IEnumerable<int> defaults, int min, int max, int keep)+ {+ var used = usedSeq.Distinct().ToList();+ int n = Math.Clamp(used.Count, min, max);+ foreach (var u in used) if (!vis.Contains(u) && vis.Count < n) vis.Add(u);+ foreach (var d in defaults) if (!vis.Contains(d) && vis.Count < Math.Max(n, min)) vis.Add(d);+ foreach (var u in used)+ if (!vis.Contains(u))+ {+ int free = -1;+ for (int i = vis.Count - 1; i >= 0 && free < 0; i--) if (i != keep && !used.Contains(vis[i])) free = i;+ if (free < 0) break; // the grid is full of routes: this one is off the grid+ vis[free] = u;+ }+ }+ var matrix = new TwinPatchMatrix+ {+ Height = 150,+ Corner = Loc.T("device.twin.matrix_corner"),+ SourceName = k => k >= 0 && k < Nota.Application.Twin.TwinMatrix.Sources.Length ? Nota.Application.Twin.TwinMatrix.Sources[k] : "",+ DestinationName = k => Nota.Application.Twin.TwinMatrix.DestinationName(engine, track, k),+ };+ var routeCount = new TextBlock { FontSize = NotaType.KnobValue, FontFamily = NotaFonts.MonoFamily, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center };+ var offGridText = new TextBlock { FontSize = NotaType.KnobLabel, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center };+ var offGrid = new Border { Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Child = Glyph.WithChevron(offGridText, 7), VerticalAlignment = VerticalAlignment.Center };+ List<TwinPatchMatrix.Cell> hidden = new();+ void SyncMatrix()+ {+ var cells = Cells();+ Fit(visRows, cells.Select(c => c.Src), DefaultMatrixRows, GridRows, MaxRows, keepRow);+ Fit(visCols, cells.Select(c => c.Dst), DefaultMatrixCols(engine, track), GridCols, MaxCols, keepCol);+ matrix.Set(visRows.ToArray(), visCols.ToArray(), cells);+ routeCount.Text = $"{cells.Count} / {Nota.Application.Twin.TwinMatrix.Slots}";+ hidden = cells.Where(c => !visRows.Contains(c.Src) || !visCols.Contains(c.Dst)).ToList();+ offGrid.IsVisible = hidden.Count > 0;+ offGridText.Text = hidden.Count > 0 ? Loc.Plural("device.twin.routes_off_the_grid", hidden.Count) : "";+ }+ readouts.Add(SyncMatrix);+ // The routes off the grid, in a menu: picking one brings its source and destination on show.+ offGrid.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(offGrid).Properties.IsLeftButtonPressed) return;+ var f = new MenuFlyout();+ foreach (var c in hidden)+ {+ var cv = c;+ var mi = new MenuItem { Header = $"{matrix.SourceName(c.Src)} → {matrix.DestinationName(c.Dst)}" };+ mi.Click += (_, _) =>+ {+ var cells = Cells();+ Put(visRows, cv.Src, -1, keepRow, cells.Select(x => x.Src).ToHashSet());+ Put(visCols, cv.Dst, -1, keepCol, cells.Select(x => x.Dst).ToHashSet());+ keepRow = visRows.IndexOf(cv.Src); keepCol = visCols.IndexOf(cv.Dst);+ Refresh();+ };+ f.Items.Add(mi);+ }+ f.ShowAt(offGrid);+ e.Handled = true;+ };+ int Slot(int s, int d) => Cells().FirstOrDefault(c => c.Src == s && c.Dst == d).Slot;+ // One drag is one undo step: a new route (Add) and its depth on both sides join one group.+ string? gestId = null, gestOther = null;+ bool creating = false;+ matrix.GestureBegin += (s, d) =>+ {+ int k = Slot(s, d);+ creating = k <= 0;+ if (creating) engine.BeginUndoGroup();+ else { gestId = $"{Part}{sideKey}.m{k}amt"; Begin(gestId); }+ };+ matrix.GestureEnd += (s, d) =>+ {+ if (gestId is not null) End(gestId);+ if (gestOther is not null) End(gestOther);+ if (creating) engine.EndUndoGroup();+ gestId = gestOther = null;+ creating = false;+ };+ matrix.DepthChanged += (s, d, v) =>+ {+ int k = Slot(s, d);+ if (k <= 0)+ {+ k = Nota.Application.Twin.TwinMatrix.Add(engine, track, s, d, v, v, PartKey);+ if (k <= 0) { ctx.Status(Loc.T("device.twin.matrix_full_64_routes")); return; }+ if (creating)+ {+ gestId = $"{Part}{sideKey}.m{k}amt"; Begin(gestId);+ gestOther = $"{Part}{otherKey}.m{k}amt"; Begin(gestOther); // a new route: both sides+ }+ SyncMatrix();+ return;+ }+ SetP($"{Part}{sideKey}.m{k}amt", 0.5f + v / 2f);+ if (gestOther is not null) SetP(gestOther, 0.5f + v / 2f);+ SyncMatrix();+ };+ matrix.Removed += (s, d) =>+ {+ int k = Slot(s, d);+ if (k > 0) Nota.Application.Twin.TwinMatrix.Remove(engine, track, k, PartKey);+ Refresh();+ };+ matrix.HeaderClicked += (isRow, i) =>+ {+ var vis = isRow ? visRows : visCols;+ void Pick(int k)+ {+ Put(vis, k, i, -1, Array.Empty<int>());+ if (isRow) keepRow = i; else keepCol = i;+ Refresh();+ }+ if (isRow) ShowSources(matrix, Pick); else ShowDestinations(matrix, Pick);+ };+ SyncMatrix();+ var matrixHint = Note(Loc.F("device.twin.matrix_hint", sideIx == 0 ? "A" : "B"));+ var routesHead = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, Children = { offGrid, routeCount } };+ Control Macros()+ {+ var g = new WrapPanel { Orientation = Orientation.Horizontal, ItemSpacing = 2, LineSpacing = 4 };+ for (int k = 1; k <= 8; k++) g.Children.Add(PKnob(Part + $"macro{k}", $"Macro {k}", Pct, cellW: 44));+ return g;+ }+ var matrixBody = Chain(+ Island("Matrix", routesHead, 412, matrix, matrixHint),+ Island("Macros", null, 0, Macros(), Note(Loc.T("device.twin.macros_are_sources_in_the_matrix"))));++ // ---- FX tab -------------------------------------------------------------+ // Mod FX ▸ Delay ▸ Reverb, each with a preview of what it does; an effect that is off greys+ // its body (it stays editable), so nothing inside it shows the accent. "All" bypasses the+ // section, for Nota's own effect devices.+ const double FxW = 178, FxK = 54;+ var dlyTimeCell = PKnob(S("dlytime"), "Time", v => NotaNum.Time(Math.Max(0.001, v * 2.0)), 44, FxK);+ var dlyDivCell = PKnob(S("dlydiv"), "Division", v => DelayDivs[Math.Clamp((int)Math.Round(v * 7), 0, 7)], 44, FxK);+ readouts.Add(() => { bool sync = G(S("dlysync")) >= 0.5f; dlyTimeCell.IsVisible = !sync; dlyDivCell.IsVisible = sync; });+ Control FxBody(string onId, params Control[] rows)+ {+ var p = new StackPanel { Spacing = 4 };+ foreach (var r in rows) p.Children.Add(r);+ return DimWhen(p, () => G(S(onId)) < 0.5f);+ }+ var modFxType = Segments(ModFxTypes, () => Sel(S("modfxtype"), 4), iv => SetParam(S("modfxtype"), iv / 3f), out var modFxTypeSync, fill: true, padX: 1, fontSize: 8);+ readouts.Add(modFxTypeSync);+ if (I(S("modfxtype")) is var mti and >= 0) MidiLearn.Bind(modFxType, MidiTarget.PluginParam(track, -1, mti), engine.PluginParamName(track, -1, mti));+ var fxBody = Chain(+ Island("Mod FX", Toggle("On", S("modfxon")), 190, FxBody("modfxon",+ modFxType, Graph(new TwinFxView(TwinFxView.Kind.ModFx), 174, 40),+ Row(PKnob(S("modfxrate"), "Rate", Pct, 44, FxK), PKnob(S("modfxdepth"), "Depth", Pct, 44, FxK), PKnob(S("modfxmix"), "Mix", Pct, 44, FxK)))),+ Island("Delay", Toggle("On", S("dlyon")), FxW, FxBody("dlyon",+ Fixed(18, Row(Toggle("Sync", S("dlysync")), new Border { Width = 6 }, Toggle("Ping-pong", S("dlypingpong")))),+ Graph(new TwinFxView(TwinFxView.Kind.Delay), 162, 40),+ Row(dlyTimeCell, dlyDivCell, PKnob(S("dlyfb"), "Feedback", Pct, 44, FxK), PKnob(S("dlymix"), "Mix", Pct, 44, FxK)))),+ Island("Reverb", Toggle("On", S("revon")), 166, FxBody("revon",+ Fixed(18), Graph(new TwinFxView(TwinFxView.Kind.Reverb), 150, 40),+ Row(PKnob(S("revsize"), "Size", Pct, 44, 49), PKnob(S("revdamp"), "Damping", Pct, 44, 49), PKnob(S("revmix"), "Mix", Pct, 44, 49)))),+ Island("All", null, 0, Toggle("On", Part + "fxon"), Note(Loc.T("device.twin.off_bypasses_all_three"))));++ // ---- Seq tab ------------------------------------------------------------+ // The patterns are structural state read from the state blob (re-read when the engine's+ // pattern revision moves); edits go through the instrument's action channel, one undo+ // step each, on the pattern the sequencer plays (seq.pattern).+ pats = null;+ int seenRev = -1, page = 0, laneSel = 0, lastPlay = -1;+ bool stepRec = false, motionRec = false;+ var grid = new TwinStepGrid { Height = 92 };+ int EditPat() => Sel("seq.pattern", 8);+ Nota.Application.Twin.TwinPatterns.Pattern? Pat() => pats?[EditPat()];+ void LoadPats() { pats = Nota.Application.Twin.TwinPatterns.FromState(engine.GetPluginState(track, -1)); }+ void SyncGrid()+ {+ grid.Pattern = Pat();+ int len = grid.Pattern?.Length ?? 16;+ page = Math.Clamp(page, 0, (len - 1) / 16);+ grid.Page = page;+ grid.Lane = laneSel;+ grid.InvalidateVisual();+ }+ void SeqAct(Nota.Application.Twin.TwinPatterns.Act a, int iarg = 0, float farg = 0f)+ {+ Nota.Application.Twin.TwinPatterns.Do(engine, track, Nota.Application.Twin.TwinPatterns.Act.SelectPattern, EditPat());+ Nota.Application.Twin.TwinPatterns.Do(engine, track, a, iarg, farg);+ LoadPats(); SyncGrid(); Refresh();+ }+ var stepInfo = new TextBlock { FontSize = NotaType.KnobValue, FontFamily = NotaFonts.MonoFamily, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center, Width = 130, TextTrimming = TextTrimming.CharacterEllipsis };+ void ShowStep()+ {+ var p = Pat();+ stepInfo.Text = p is null || grid.Selected < 0 || grid.Selected >= p.Length ? Loc.T("device.twin.click_a_step")+ : Loc.F("device.twin.step_n_text", grid.Selected + 1, Nota.Application.Twin.TwinPatterns.StepText(p.Steps[grid.Selected]));+ }+ grid.SelectStep = _ => ShowStep();+ grid.CommitVelocity = (st, v) => SeqAct(Nota.Application.Twin.TwinPatterns.Act.SetStepVelocity, st, v / 127f);+ grid.CommitGate = (st, g) => SeqAct(Nota.Application.Twin.TwinPatterns.Act.SetStepGate, st, g >= Nota.Application.Twin.TwinPatterns.GateTie ? 1.01f : g / 100f);+ readouts.Add(() => { if (pats is null) LoadPats(); SyncGrid(); ShowStep(); });+ // The record switches live on this card: when it goes (a rebuild — A / B, the part, the+ // layout — or another track), recording stops rather than staying armed out of sight.+ grid.DetachedFromVisualTree += (_, _) =>+ {+ if (stepRec) Nota.Application.Twin.TwinPatterns.Do(engine, track, Nota.Application.Twin.TwinPatterns.Act.StepRecordArm, 0);+ if (motionRec) Nota.Application.Twin.TwinPatterns.Do(engine, track, Nota.Application.Twin.TwinPatterns.Act.MotionRecordArm, -1);+ stepRec = motionRec = false;+ };++ Control SeqPicker(Func<string> text, string tip, Func<string[]> items, Action<int> pick)+ {+ var tb = new TextBlock { FontSize = NotaType.RowLabel, Foreground = TextPrimary, VerticalAlignment = VerticalAlignment.Center };+ var host = new Border { Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Padding = new Thickness(3, 0), Child = Glyph.WithChevron(tb, 7), VerticalAlignment = VerticalAlignment.Center };+ ToolTip.SetTip(host, tip);+ readouts.Add(() => tb.Text = text());+ tb.Text = text();+ host.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(host).Properties.IsLeftButtonPressed) return;+ var f = new MenuFlyout();+ var list = items();+ for (int k = 0; k < list.Length; k++) { int kv = k; var mi = new MenuItem { Header = list[k] }; mi.Click += (_, _) => pick(kv); f.Items.Add(mi); }+ f.ShowAt(host); e.Handled = true;+ };+ return host;+ }+ Control TextAction(string text, string tip, Action act)+ {+ var b = TextButton(text);+ b.Padding = new Thickness(6, 1);+ ToolTip.SetTip(b, tip);+ b.VerticalAlignment = VerticalAlignment.Center;+ b.PointerPressed += (_, e) => { if (e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) { act(); e.Handled = true; } };+ return b;+ }+ // A text action that is on (recording, learning): a solid accent key with derived ink.+ static void Lit(Control c, bool on)+ {+ if (c is not Border b) return;+ b.Background = on ? Brass : Raised;+ if (b.Child is TextBlock t) t.Foreground = on ? OnAccent : TextPrimary;+ }+ var patPick = SeqPicker(() => $"Pattern {EditPat() + 1}", Loc.T("device.twin.the_pattern_that_plays_and_you_edit"),+ () => Enumerable.Range(1, 8).Select(i => $"Pattern {i}").ToArray(), k => { SetParam("seq.pattern", k / 7f); page = 0; LoadPats(); SyncGrid(); });+ var lenPick = SeqPicker(() => $"{Pat()?.Length ?? 16} steps", Loc.T("device.twin.pattern_length"), () => SeqLengths.Select(n => $"{n} steps").ToArray(),+ k => SeqAct(Nota.Application.Twin.TwinPatterns.Act.SetLength, SeqLengths[k]));+ var ratePick = SeqPicker(() => SeqRates[Sel("seq.rate", 6)], Loc.T("device.twin.step_rate"), () => SeqRates, k => SetParam("seq.rate", k / 5f));+ var recBtn = TextAction(Loc.T("common.record"), Loc.T("device.twin.step_record_play_a_chord"), () =>+ {+ stepRec = !stepRec;+ Nota.Application.Twin.TwinPatterns.Do(engine, track, Nota.Application.Twin.TwinPatterns.Act.SelectPattern, EditPat());+ Nota.Application.Twin.TwinPatterns.Do(engine, track, Nota.Application.Twin.TwinPatterns.Act.StepRecordArm, stepRec ? 1 : 0);+ Refresh();+ });+ readouts.Add(() => Lit(recBtn, stepRec));+ var toClip = TextAction(Loc.T("device.twin.to_clip"), Loc.T("device.twin.write_this_pattern_as_a_midi_clip"), () =>+ {+ double at = Math.Floor(engine.PositionBeats / 4.0) * 4.0;+ // A clip plays the parts as the keys do; say so when that isn't how the pattern plays.+ switch (Nota.Application.Twin.TwinPatterns.ToClipBlock(engine, track, EditPat()))+ {+ case Nota.Application.Twin.TwinPatterns.ClipBlock.LayerOnePart: ctx.Status(Loc.T("device.twin.to_clip_layer_one_part")); return;+ case Nota.Application.Twin.TwinPatterns.ClipBlock.SplitBothParts: ctx.Status(Loc.T("device.twin.to_clip_split_both_parts")); return;+ case Nota.Application.Twin.TwinPatterns.ClipBlock.SplitOtherSide: ctx.Status(Loc.T("device.twin.to_clip_split_other_side")); return;+ case Nota.Application.Twin.TwinPatterns.ClipBlock.InRack: ctx.Status(Loc.T("device.twin.to_clip_in_rack")); return;+ }+ Nota.Application.Twin.TwinPatterns.ToClip(engine, track, EditPat(), at);+ ctx.NotifyChanged(); Refresh();+ });+ var pagePick = Segments(new[] { "1–16", "17–32", "33–48", "49–64" }, () => page, k => { page = k; SyncGrid(); }, out var pageSync, padX: 3);+ readouts.Add(() => { pageSync(); pagePick.IsVisible = (Pat()?.Length ?? 16) > 16; });+ var restBtn = TextAction(Loc.T("device.twin.rest"), Loc.T("device.twin.make_the_selected_step_a_rest"), () => { if (grid.Selected >= 0) SeqAct(Nota.Application.Twin.TwinPatterns.Act.ClearStep, grid.Selected); });+ var laneTargets = new List<(string Name, int Index)> { ("None", -1), ("Morph", I(Part + "morph")), ("Pad X", I("padx")), ("Pad Y", I("pady")), ("Pad Z", I("padz")) };+ foreach (var id in Nota.Application.Twin.TwinMatrix.SideDestinationIds)+ if (I(Side + id) is var li and >= 0) laneTargets.Add((Nota.Application.Twin.TwinMatrix.DestinationName(engine, track, Nota.Application.Twin.TwinMatrix.DestinationOfSide(id)) + $" ({(sideIx == 0 ? "A" : "B")})", li));+ var lanePick = Segments(new[] { "1", "2", "3", "4" }, () => laneSel, k =>+ {+ laneSel = k;+ // Recording moves with the lane: the engine pauses the lane being recorded, not the old one.+ if (motionRec) Nota.Application.Twin.TwinPatterns.Do(engine, track, Nota.Application.Twin.TwinPatterns.Act.MotionRecordArm, laneSel);+ SyncGrid(); Refresh();+ }, out var laneSync, padX: 4);+ readouts.Add(laneSync);+ var targetPick = SeqPicker(() =>+ {+ int tg = Pat()?.Lanes[laneSel].Target ?? -1;+ return tg < 0 ? Loc.T("device.twin.no_target") : laneTargets.FirstOrDefault(x => x.Index == tg).Name ?? engine.PluginParamName(track, -1, tg);+ }, Loc.T("device.twin.what_this_motion_lane_sets"), () => laneTargets.Select(x => x.Name).ToArray(),+ k => SeqAct(Nota.Application.Twin.TwinPatterns.Act.MotionTarget, laneSel << 16 | (laneTargets[k].Index < 0 ? 0xFFFF : laneTargets[k].Index)));+ var motionRecBtn = TextAction(Loc.T("device.twin.rec_motion"), Loc.T("device.twin.record_the_lane"), () =>+ {+ motionRec = !motionRec;+ Nota.Application.Twin.TwinPatterns.Do(engine, track, Nota.Application.Twin.TwinPatterns.Act.MotionRecordArm, motionRec ? laneSel : -1);+ Refresh();+ });+ readouts.Add(() => Lit(motionRecBtn, motionRec));+ var clearLane = TextAction(Loc.T("common.clear"), Loc.T("device.twin.clear_the_lane"), () => SeqAct(Nota.Application.Twin.TwinPatterns.Act.ClearMotion, laneSel));+ var smoothSw = Switch("Smooth", () => Pat()?.Lanes[laneSel].Smooth ?? false,+ () => SeqAct(Nota.Application.Twin.TwinPatterns.Act.MotionMode, laneSel, Pat()?.Lanes[laneSel].Smooth == true ? 0f : 1f), out var smoothSync);+ ToolTip.SetTip(smoothSw, Loc.T("device.twin.glide_from_step_to_step"));+ readouts.Add(smoothSync);+ // Live: the playing step, the record cursor, chords played while recording, recorded motion.+ var seqScope = new float[32];+ ctx.AddDeviceRefresher(() =>+ {+ if (engine.InstrumentScope(track, seqScope) < 25) return;+ if ((int)seqScope[3] != seenRev) { seenRev = (int)seqScope[3]; LoadPats(); }+ int play = (int)seqScope[0];+ if (stepRec) Nota.Application.Twin.TwinPatterns.Do(engine, track, Nota.Application.Twin.TwinPatterns.Act.StepRecordPoll);+ if (motionRec && play >= 0 && play != lastPlay && Pat()?.Lanes[laneSel].Target is int tg and >= 0)+ Nota.Application.Twin.TwinPatterns.Do(engine, track, Nota.Application.Twin.TwinPatterns.Act.MotionSet, laneSel << 8 | play, engine.PluginParamGet(track, -1, tg));+ lastPlay = play;+ grid.PlayStep = play;+ grid.RecStep = (int)seqScope[24];+ SyncGrid();+ });+ // Swing as a table-row knob with its value beside it (the row stays one line tall).+ Control SeqSwing()+ {+ int si = I("seq.swing");+ var value = new TextBlock { Width = 30, FontSize = NotaType.KnobValue, FontFamily = NotaFonts.MonoFamily, Foreground = TextPrimary, VerticalAlignment = VerticalAlignment.Center };+ var knob = new Knob(G("seq.swing"), 1.0) { Inline = true, Accent = true, Default = 0, Format = v => Pct((float)v) };+ knob.ValueChanged += v => { SetP("seq.swing", (float)v); value.Text = Pct((float)v); };+ knob.GestureBegin += () => Begin("seq.swing");+ knob.GestureEnd += () => End("seq.swing");+ if (si >= 0) { ctx.AddInstFader(si, knob, value, Pct); MidiLearn.Bind(knob, MidiTarget.PluginParam(track, -1, si), "Sequencer Swing"); }+ value.Text = Pct(G("seq.swing"));+ return new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2, VerticalAlignment = VerticalAlignment.Center, Children = { knob, value } };+ }+ var steps = Note("Steps");+ var pageRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Children = { steps, pagePick } };+ readouts.Add(() => steps.IsVisible = pagePick.IsVisible);+ Control Bar(Control left, Control? right = null)+ {+ var d = new DockPanel { LastChildFill = false, Height = 18 };+ if (right is not null) { DockPanel.SetDock(right, Dock.Right); d.Children.Add(right); }+ DockPanel.SetDock(left, Dock.Left); d.Children.Add(left);+ return d;+ }+ StackPanel Line(params Control[] cs)+ {+ var p = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center };+ foreach (var c in cs) { c.VerticalAlignment = VerticalAlignment.Center; p.Children.Add(c); }+ return p;+ }+ // What to do next: switch it on, fill the pattern, or play it (a key, or the transport).+ var seqHint = Note(Loc.T("device.twin.seq_hint"));+ readouts.Add(() => seqHint.Text = G("seq.on") < 0.5f ? Loc.T("device.twin.seq_turn_on")+ : Pat() is { } sp && sp.Steps.Take(sp.Length).All(st => st.IsRest) ? Loc.T("device.twin.seq_empty") : Loc.T("device.twin.seq_hint"));+ var seqPage = new StackPanel+ {+ Spacing = 4,+ Children =+ {+ Bar(Line(patPick, lenPick, ratePick, Cap("Swing"), SeqSwing(), Toggle("Transpose", "seq.transpose"), Toggle("Latch", "seq.latch"))),+ grid,+ Bar(Line(Cap("Motion"), lanePick, targetPick, smoothSw, motionRecBtn, clearLane), pageRow),+ Bar(Line(stepInfo, restBtn), seqHint),+ },+ };+ var arpHint = Note(Loc.T("device.twin.arp_hint"));+ arpHint.Width = 300;+ readouts.Add(() => arpHint.Text = G("seq.on") < 0.5f ? Loc.T("device.twin.seq_turn_on") : Loc.T("device.twin.arp_hint"));+ var arpKnobs = Row(PKnob("arp.gate", "Gate", Pct, 44, 64), PKnob("seq.swing", "Swing", Pct, 44, 64));+ arpKnobs.HorizontalAlignment = HorizontalAlignment.Left;+ var arpPage = new StackPanel+ {+ Spacing = 10,+ Children =+ {+ Bar(Line(Cap("Mode"), SeqPicker(() => ArpModes[Sel("arp.mode", 6)], Loc.T("device.twin.arpeggio_order"), () => ArpModes, k => SetParam("arp.mode", k / 5f)),+ Cap("Rate"), SeqPicker(() => SeqRates[Sel("seq.rate", 6)], Loc.T("device.twin.step_rate"), () => SeqRates, k => SetParam("seq.rate", k / 5f)),+ Cap("Octaves"), Chips("arp.oct", new[] { "1", "2", "3", "4" }, 4), Toggle("Hold", "arp.hold"))),+ Line(arpKnobs, arpHint),+ },+ };+ readouts.Add(() => { bool arp = G("seq.kind") >= 0.5f; seqPage.IsVisible = !arp; arpPage.IsVisible = arp; recBtn.IsVisible = !arp; toClip.IsVisible = !arp; });+ // The header carries what acts on the whole sequencer: the part it plays, record, to clip,+ // on, and Seq / Arp.+ var seqHead = Line();+ if (layout != 0)+ {+ var target = Chips("seq.target", SeqTargets, 4);+ ToolTip.SetTip(target, Loc.T("device.twin.the_part_the_sequencer_plays"));+ seqHead.Children.Add(Cap("Plays"));+ seqHead.Children.Add(target);+ }+ foreach (var c in new[] { recBtn, toClip, Toggle("On", "seq.on"), Chips("seq.kind", new[] { "Seq", "Arp" }, 5) }) { c.VerticalAlignment = VerticalAlignment.Center; seqHead.Children.Add(c); }+ var seqBody = Chain(Island("Sequencer", seqHead, 0, new Panel { Children = { seqPage, arpPage } }));++ // ---- Voice tab ----------------------------------------------------------+ // Voices ▸ Stereo ▸ Output (in Layer / Split the part's own section: volume, pan, octave,+ // the split key — learnable from a played key, Split only — and the voice share) ▸ Pad.+ // The section's Parts menu copies, swaps or loads the parts.+ // Parts: copy / swap them, or load a factory sound into one (Upper of a Single patch → Layer).+ // The user's saved Nota Twin presets (the app's presets folder), with their params.+ static IEnumerable<(string Path, string Title, IReadOnlyDictionary<string, float> Params)> UserTwinPresets()+ {+ if (App.Services?.GetService(typeof(IPresetLibrary)) is not IPresetLibrary lib+ || App.Services.GetService(typeof(IPresetStore)) is not IPresetStore store+ || App.Services.GetService(typeof(ISettingsService)) is not ISettingsService settings) yield break;+ foreach (var p in lib.List(settings.PresetsFolder()))+ if (p.Type == "builtin-instrument" && store.Describe(p.Path) is { BuiltinKind: Nota.Application.Twin.TwinMatrix.Kind }+ && store.InstrumentParams(p.Path) is { } prm)+ yield return (p.Path, p.DisplayName, prm);+ }+ Control partsMenu = null!;+ partsMenu = TextAction("Parts", Loc.T("device.twin.copy_or_swap_the_parts"), () =>+ {+ var f = new MenuFlyout();+ void Item(ItemsControl into, string header, Action act)+ {+ var mi = new MenuItem { Header = header };+ mi.Click += (_, _) => { act(); ctx.NotifyChanged(); ctx.RequestRebuild(); };+ into.Items.Add(mi);+ }+ var menu = new MenuItem(); // a holder: its items move into the flyout below+ if (layout != 0)+ {+ Item(menu, Loc.T("device.twin.copy_lower_to_upper"), () => Nota.Application.Twin.TwinParts.Apply(engine, track, Nota.Application.Twin.TwinParts.Edit.CopyLowerToUpper));+ Item(menu, Loc.T("device.twin.copy_upper_to_lower"), () => Nota.Application.Twin.TwinParts.Apply(engine, track, Nota.Application.Twin.TwinParts.Edit.CopyUpperToLower));+ Item(menu, Loc.T("device.twin.swap_parts"), () => Nota.Application.Twin.TwinParts.Apply(engine, track, Nota.Application.Twin.TwinParts.Edit.Swap));+ }+ foreach (var (part, name) in new[] { ("lo", Loc.T("device.twin.load_into_lower")), ("up", Loc.T("device.twin.load_into_upper")) })+ {+ var sub = new MenuItem { Header = name };+ foreach (var p in ctx.Factory?.All() ?? Array.Empty<FactoryPresetInfo>())+ {+ if (!p.IsInstrument || p.BuiltinKind != Nota.Application.Twin.TwinMatrix.Kind || ctx.Factory!.InstrumentParams(p.Id) is not { } prm) continue;+ Item(sub, p.DisplayName, () =>+ {+ Nota.Application.Twin.TwinParts.LoadIntoPart(engine, track, prm, part);+ EditParts[track] = part == "lo" ? 0 : 1;+ });+ }+ // The user's own Twin presets, after the factory ones.+ bool first = true;+ foreach (var (path, title, prm) in UserTwinPresets())+ {+ if (first && sub.Items.Count > 0) sub.Items.Add(new Separator());+ first = false;+ Item(sub, title, () =>+ {+ Nota.Application.Twin.TwinParts.LoadIntoPart(engine, track, prm, part);+ EditParts[track] = part == "lo" ? 0 : 1;+ });+ }+ sub.IsEnabled = sub.Items.Count > 0;+ menu.Items.Add(sub);+ }+ foreach (var it in menu.Items.Cast<MenuItem>().ToList()) { menu.Items.Remove(it); f.Items.Add(it); }+ f.ShowAt(partsMenu);+ });+ Control BendRange()+ {+ var seg = Chips("bendrange", new[] { "±2", "±5", "±12", "±24" }, 5);+ ToolTip.SetTip(seg, Loc.T("device.twin.pitch_bend_range_in_semitones"));+ return new StackPanel { Spacing = 3, Children = { Cap("Bend range"), seg } };+ }+ Control Output()+ {+ if (layout == 0)+ return Island("Output", partsMenu, 140,+ Row(PKnob(Part + "vol", "Volume", Pct, 44, 58), PKnob(Part + "pan", "Pan", PanText, 44, 58)), BendRange());+ bool learn = false;+ int lastKey = int.MinValue;+ var learnBtn = TextAction(Loc.T("device.twin.learn"), Loc.T("device.twin.play_a_key_it_becomes_the_split"), () => { learn = !learn; lastKey = int.MinValue; Refresh(); });+ readouts.Add(() => Lit(learnBtn, learn));+ var keyScope = new float[32];+ ctx.AddDeviceRefresher(() =>+ {+ if (!learn || engine.InstrumentScope(track, keyScope) < 26) return;+ int k = (int)keyScope[25];+ if (lastKey != int.MinValue && k >= 0 && k != lastKey) { learn = false; SetParam("splitkey", k / 127f); }+ lastKey = k;+ });+ string ShareText(float v)+ {+ int cap = 4 + Math.Clamp((int)Math.Round(G("voices") * 8), 0, 8), lo = LowerShare(v, cap);+ return $"{lo} + {cap - lo}";+ }+ var second = layout == 2+ ? Row(PKnob("splitkey", "Split", SplitKey, cellW: 46), PKnob("share", "Voices", ShareText, cellW: 46), new Border { Padding = new Thickness(2, 10, 0, 0), Child = learnBtn })+ : Row(PKnob("share", "Voices", ShareText, cellW: 46));+ second.HorizontalAlignment = HorizontalAlignment.Left;+ var first = Row(PKnob(Part + "vol", "Volume", Pct, cellW: 46), PKnob(Part + "pan", "Pan", PanText, cellW: 46), PKnob(Part + "octave", "Octave", Octave, cellW: 46));+ first.HorizontalAlignment = HorizontalAlignment.Left;+ return Island($"{PartNames[partIx]} part", partsMenu, 160, first, second, BendRange());+ }+ int VoiceMode() => Sel(Part + "voicemode", 4);+ var detune = DimWhen(PKnob(S("unidetune"), "Detune", Detune, 44, 58), () => VoiceMode() != 3);+ var detuneNote = Note(Loc.T("device.twin.detune_works_in_unison"));+ readouts.Add(() => detuneNote.IsVisible = VoiceMode() != 3);+ var spreadBy = Chips(S("spreadmode"), SpreadModes, 5);+ var padNote = Note(Loc.T("device.twin.pad_hint_short"));+ var voiceBody = Chain(+ Island("Voices", Chips(Part + "voicemode", VoiceModes, 4), 200,+ Row(PKnob("voices", "Voices", Voices, 44, 58), PKnob(Part + "glide", "Glide", Glide, 44, 58), detune),+ Toggle("Glide only legato", Part + "glidelegato"), detuneNote),+ Island("Stereo", null, layout == 0 ? 132 : 118,+ Row(PKnob(S("spread"), "Spread", Pct, 44, 54), PKnob(S("drift"), "Drift", Pct, 44, 54)),+ new StackPanel { Spacing = 3, Children = { Cap("Spread by"), spreadBy } }),+ Output(),+ Island("Pad", null, 0, PadView(layout == 0 ? 104 : 96), padNote));++ var bodies = new Control[] { oscBody, filterBody, envBody, lfoBody, matrixBody, fxBody, seqBody, voiceBody };+ var tabCells = new Border[TabNames.Length];+ var tabTexts = new TextBlock[TabNames.Length];+ var tabRow = new StackPanel { Orientation = Orientation.Horizontal };+ for (int i = 0; i < TabNames.Length; i++)+ {+ int iv = i;+ var tb = new TextBlock { Text = TabNames[i], FontSize = NotaType.DeviceSection, FontWeight = FontWeight.SemiBold, VerticalAlignment = VerticalAlignment.Center };+ var cell = new Border { Padding = new Thickness(7, 0), BorderThickness = new Thickness(0, 0, 0, 2), Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Child = tb };+ cell.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(cell).Properties.IsLeftButtonPressed) return;+ tab = iv; OpenTabs[track] = iv; showTab(); e.Handled = true;+ };+ cell.PointerEntered += (_, _) => { if (iv != tab) tb.Foreground = TextPrimary; };+ cell.PointerExited += (_, _) => { if (iv != tab) tb.Foreground = TextTertiary; };+ tabCells[i] = cell; tabTexts[i] = tb; tabRow.Children.Add(cell);+ }+ // The chosen tab: heading ink over a 2 px accent underline (chosen is what the accent is for).+ showTab = () =>+ {+ for (int i = 0; i < TabNames.Length; i++)+ {+ bool on = i == tab;+ tabCells[i].BorderBrush = on ? Brass : Brushes.Transparent;+ tabTexts[i].Foreground = on ? NotaPalette.TextHeading : TextTertiary;+ bodies[i].IsVisible = on;+ }+ Refresh();+ };+ var tabHost = new Panel { ClipToBounds = true };+ foreach (var b in bodies) tabHost.Children.Add(b);+ var tabGrid = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };+ // Right of the tabs: in Layer / Split the part every tab edits, then Single / Layer / Split.+ var layoutSeg = Segments(Layouts, () => layout, iv =>+ {+ if (iv == layout) return;+ SetParam("mode", iv / 2f);+ ctx.RequestRebuild();+ }, out var layoutSync, padX: 6);+ ToolTip.SetTip(layoutSeg, Loc.T("device.twin.one_sound_two_layered_or_split"));+ readouts.Add(layoutSync);+ var partBar = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Margin = new Thickness(0, 0, 0, 2), VerticalAlignment = VerticalAlignment.Center, Children = { layoutSeg } };+ if (layout != 0)+ {+ var partSeg = Segments(PartNames, () => partIx, iv =>+ {+ if (iv == partIx) return;+ EditParts[track] = iv;+ ctx.RequestRebuild();+ }, out var partSync, padX: 6);+ ToolTip.SetTip(partSeg, Loc.T("device.twin.the_part_every_tab_edits"));+ readouts.Add(partSync);+ partBar.Children.Insert(0, partSeg);+ }+ var tabBar = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };+ tabBar.Children.Add(tabRow);+ Grid.SetColumn(partBar, 1); tabBar.Children.Add(partBar);+ tabGrid.Children.Add(new Border { Height = TabH, BorderBrush = NotaPalette.Rule, BorderThickness = new Thickness(0, 0, 0, 1), Child = tabBar });+ Grid.SetRow(tabHost, 1); tabGrid.Children.Add(tabHost);+ var tabPanel = Section(tabGrid);++ // ---- the morph column ---------------------------------------------------+ // Morph (main knob), where it sounds now between A and B (the edited end in the accent),+ // the side the knobs edit, and the side copies as quiet actions.+ var scope = new float[32];+ Control MorphColumn(bool actions)+ {+ var col = new StackPanel { Spacing = 3, Margin = new Thickness(0, 2, 0, 0), HorizontalAlignment = HorizontalAlignment.Center, Width = 58 };+ var title = Title("Morph"); title.HorizontalAlignment = HorizontalAlignment.Center;+ col.Children.Add(title);+ col.Children.Add(PKnob(Part + "morph", "", v => NotaNum.Pct(v), 44, 58));+ // The part (accent) and every sounding voice (dots), live, with A and B at the ends.+ var strip = new TwinMorphStrip { Height = 8, VerticalAlignment = VerticalAlignment.Center };+ ToolTip.SetTip(strip, Loc.T("device.twin.the_morph_as_it_sounds_now"));+ TextBlock End(string t, bool edited) => new()+ {+ Text = t, FontFamily = NotaFonts.MonoFamily, FontSize = NotaType.KnobValue, VerticalAlignment = VerticalAlignment.Center,+ Foreground = edited ? Brass : NotaPalette.TextFaint,+ };+ var ends = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 2 };+ var ea = End("A", sideIx == 0); var eb = End("B", sideIx == 1);+ Grid.SetColumn(strip, 1); Grid.SetColumn(eb, 2);+ ends.Children.Add(ea); ends.Children.Add(strip); ends.Children.Add(eb);+ col.Children.Add(ends);+ ctx.AddDeviceRefresher(() =>+ {+ int got = engine.InstrumentScope(track, scope);+ if (got < 23) return;+ int cap = 4 + Math.Clamp((int)Math.Round(G("voices") * 8), 0, 8), lo = layout == 0 ? cap : LowerShare(G("share"), cap);+ strip.Set(scope[6 + partIx], partIx == 0 ? scope.AsSpan(8, lo) : scope.AsSpan(8 + lo, cap - lo));+ for (int l = 0; l < 3; l++)+ if (lfoGraphs[l] is { } lg) { lg.Phase = scope[20 + l]; lg.Refresh(); }+ });+ var editCap = Cap(Loc.T("device.twin.edit")); editCap.HorizontalAlignment = HorizontalAlignment.Center; editCap.Margin = new Thickness(0, 8, 0, 0);+ col.Children.Add(editCap);+ var sideSeg = Segments(new[] { "A", "B" }, () => sideIx, iv =>+ {+ if (iv == sideIx) return;+ EditSides[track] = iv;+ ctx.RequestRebuild();+ }, out var sideSync, fill: true, fontSize: NotaType.DeviceSection);+ readouts.Add(sideSync);+ ToolTip.SetTip(sideSeg, Loc.T("device.twin.the_side_the_knobs_edit"));+ col.Children.Add(sideSeg);+ if (!actions) return col;+ // A quiet action: no frame at rest, a hover tone; it rewrites a side in one undo step.+ Control SideAction(string text, string tip, Nota.Application.Twin.TwinSides.Edit edit)+ {+ var tb = new TextBlock { Text = text, FontSize = NotaType.RowLabel, FontWeight = FontWeight.Medium, Foreground = TextSecondary, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };+ var b = new Border { Height = 16, CornerRadius = NotaRadius.Clip, Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), Child = tb };+ b.PointerEntered += (_, _) => { b.Background = NotaPalette.SurfaceHover; tb.Foreground = TextPrimary; };+ b.PointerExited += (_, _) => { b.Background = Brushes.Transparent; tb.Foreground = TextSecondary; };+ ToolTip.SetTip(b, tip);+ b.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return;+ Nota.Application.Twin.TwinSides.Apply(engine, track, edit, PartKey);+ ctx.NotifyChanged();+ ctx.RequestRebuild();+ e.Handled = true;+ };+ return b;+ }+ col.Children.Add(new StackPanel+ {+ Spacing = 2, Margin = new Thickness(0, 8, 0, 0),+ Children =+ {+ SideAction("A → B", Loc.T("device.twin.copy_side_a_onto_side_b"), Nota.Application.Twin.TwinSides.Edit.CopyAToB),+ SideAction("B → A", Loc.T("device.twin.copy_side_b_onto_side_a"), Nota.Application.Twin.TwinSides.Edit.CopyBToA),+ SideAction(Loc.T("device.twin.swap"), Loc.T("device.twin.swap_sides_a_and_b"), Nota.Application.Twin.TwinSides.Edit.Swap),+ },+ });+ return col;+ }++ // ---- assembly -----------------------------------------------------------+ bool mini = InstrumentView.IsMini(engine, track);+ var morphPanel = Section(MorphColumn(!mini));+ morphPanel.Width = mini ? 64 : MorphW;+ var body = new Grid+ {+ ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 0,+ Margin = new Thickness(NotaSpace.DeviceInset),+ };+ body.Children.Add(morphPanel);+ Control main = tabPanel;+ if (mini)+ {+ // S: the same params, fewer of them — Morph and A / B, the pad, four sound knobs.+ var knobs = Row(PKnob(S("ldcut"), "Cutoff", Cutoff, cellW: 42), PKnob(S("ldres"), "Reso", Pct, cellW: 42),+ PKnob(S("aenva"), "Attack", Attack, cellW: 42), PKnob(S("aenvr"), "Release", Decay, cellW: 42));+ var pad = PadView(124, legend: false, width: 172);+ pad.HorizontalAlignment = HorizontalAlignment.Center;+ var stack = new DockPanel { LastChildFill = false, Margin = new Thickness(6, 2, 0, 0) };+ DockPanel.SetDock(pad, Dock.Top); DockPanel.SetDock(knobs, Dock.Bottom);+ stack.Children.Add(pad); stack.Children.Add(knobs);+ main = Section(stack);+ }+ Grid.SetColumn(main, 1); body.Children.Add(main);+ var root = new Border { Background = NotaPalette.SurfaceCard, Child = body };++ ctx.SetInstLiveViz(Refresh);+ showTab();+ return root;+ }+}diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.csindex 102672fa..9ba89ec3 100644--- a/src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs@@ -510,7 +510,7 @@ internal sealed partial class RackCardViewvar f = new MenuFlyout();void Add(string h, int k) { var mi = new MenuItem { Header = h }; mi.Click += (_, _) => { _ra.SetChainInstrument(c, k); DeferRebuild(); }; f.Items.Add(mi); }Add("Nota Volt", 6); Add("Nota Physical", 2); Add("Nota Aurora", 5); Add("Nota Pendulum", 8); Add("Nota Operator", 9); Add("Nota Grain", 10);- Add("Nota Flux", 11); Add("Nota Monolith", 13); Add("Nota Pentad", 14); Add("Nota Consort", 15); Add("Nota Keys", 16);+ Add("Nota Flux", 11); Add("Nota Monolith", 13); Add("Nota Pentad", 14); Add("Nota Consort", 15); Add("Nota Keys", 16); Add("Nota Twin", 18);Add("Nota Mosaic", 17);// A Drum Rack in a chain: racks nest one level (specs/041).f.Items.Add(new Separator()); Add("Nota Drum Rack", 4);diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.Drum.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.Drum.csindex 8d320c78..a3246614 100644--- a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.Drum.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.Drum.cs@@ -856,6 +856,7 @@ internal sealed partial class RackCardViewAdd("Nota Consort", 15);Add("Nota Keys", 16);Add("Nota Mosaic", 17);+ Add("Nota Twin", 18);f.ShowAt(anchor, showAtPointer: true);}diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.csindex 6fe7335c..1a75b9ea 100644--- a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs@@ -226,7 +226,7 @@ internal sealed partial class RackCardView(DeviceCardContext ctx){bool two = InstrumentView.Index(proxy, T) >= 0;double w = strategy.BodyOnly ? strategy.WidthFor(proxy, T) : 700;- return new DeviceWindowPage(BuildChainInstrumentBespoke(ik, sc, tickReg, w), w, CardBodyH, WindowPresets(presets, () => win.Refill()),+ return new DeviceWindowPage(BuildChainInstrumentBespoke(ik, sc, tickReg, w, () => win.Refill()), w, CardBodyH, WindowPresets(presets, () => win.Refill()),two ? new DeviceWindowSize(InstrumentView.IsMini(proxy, T), m => InstrumentView.SetMini(proxy, T, m)) : null);}, status: () => InstrumentStatus(a, sc, proxy, strategy)) { ContextTrackId = T };win.ShowFrom(anchor);@@ -405,14 +405,16 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)// Host a built-in instrument's own editor for a rack chain: a DispatchProxy redirects// the editor's plugin-param calls (track, -1, i) to the chain surface (track, chain, i);- // a local tick drives its live graphs + knob follow.- private Control BuildChainInstrumentBespoke(int ik, int sc, Action<Action> tickReg, double width = 700)+ // a local tick drives its live graphs + knob follow. rebuild: what the card's RequestRebuild+ // does (a Nota Twin's A / B, part and layout switches rebuild it) — the window refills.+ private Control BuildChainInstrumentBespoke(int ik, int sc, Action<Action> tickReg, double width = 700, Action? rebuild = null){var proxy = ChainInstrumentProxy(sc);var faders = new System.Collections.Generic.List<(int i, Knob k, TextBlock v, Func<float, string>? fmt)>();Action? viz = null;+ Action requestRebuild = rebuild is null ? () => { } : () => Avalonia.Threading.Dispatcher.UIThread.Post(rebuild);var ctx = new DeviceCardContext(proxy, T, tickReg, () => { }, (i, k, v, f) => faders.Add((i, k, v, f)), v => viz = v,- _ => { }, () => 0, _ => { }, tickReg, () => { }, () => { }, _ => { }, () => { }, _ctx.Factory);+ _ => { }, () => 0, _ => { }, tickReg, () => { }, requestRebuild, _ => { }, () => { }, _ctx.Factory);var body = _irFactory.Resolve(ik, true).Build(ctx);tickReg(() => { viz?.Invoke(); foreach (var f in faders) { if (f.k.Dragging) continue; float v = proxy.PluginParamGet(T, -1, f.i); if (Math.Abs(v - f.k.Value) > 1e-3) { f.k.Value = v; f.v.Text = (f.fmt ?? Pct)(v); } } });return new Border { Width = width, Height = CardBodyH, Background = NotaPalette.BgApp, ClipToBounds = true, Child = body };@@ -478,7 +480,7 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)var f = new MenuFlyout();void Add(string h, int k) { var mi = new MenuItem { Header = h }; mi.Click += (_, _) => { int c = a.AddChain(k); if (c >= 0) Sel = c; _ctx.RequestRebuild(); }; f.Items.Add(mi); }Add("Nota Volt", 6); Add("Nota Sampler", 1); Add("Nota Physical", 2); Add("Nota Aurora", 5);- Add("Nota Pendulum", 8); Add("Nota Operator", 9); Add("Nota Grain", 10); Add("Nota Flux", 11); Add("Nota Monolith", 13); Add("Nota Pentad", 14); Add("Nota Consort", 15); Add("Nota Keys", 16);+ Add("Nota Pendulum", 8); Add("Nota Operator", 9); Add("Nota Grain", 10); Add("Nota Flux", 11); Add("Nota Monolith", 13); Add("Nota Pentad", 14); Add("Nota Consort", 15); Add("Nota Keys", 16); Add("Nota Twin", 18);Add("Nota Mosaic", 17);f.Items.Add(new Separator()); Add("Nota Drum Rack", 4); // racks nest one level (specs/041)f.ShowAt(anchor, showAtPointer: true);diff --git a/src/managed/Nota.App/NotaDocs.cs b/src/managed/Nota.App/NotaDocs.csindex 7118efd1..3c3d5e27 100644--- a/src/managed/Nota.App/NotaDocs.cs+++ b/src/managed/Nota.App/NotaDocs.cs@@ -23,7 +23,7 @@ internal static class NotaDocs"racks/drum-rack", "instruments/aurora", "instruments/volt", "instruments/bass","instruments/pendulum", "instruments/operator", "instruments/grain", "instruments/flux","instruments/rhythm", "instruments/monolith", "instruments/pentad", "instruments/consort",- "instruments/keys", "instruments/mosaic",+ "instruments/keys", "instruments/mosaic", "instruments/twin",};private static readonly string[] AudioEffects ={diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex e8908303..63709e98 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -426,6 +426,8 @@ public interface IAudioEngine : IDisposable/// <summary>Adds an instrument track with the built-in Nota Mosaic multisample instrument (kind 17),/// empty until a program is set.</summary>int AddMosaicTrack();+ /// <summary>Adds an instrument track with the built-in Nota Twin two-part morphing analog poly (kind 18).</summary>+ int AddTwinTrack();/// <summary>Sets a Nota Mosaic's program (MosaicProgram text) and starts loading its samples in/// the background. <paramref name="undoable"/>: one undo step (sounding notes stop); false edits/// the live instrument in place (a drag in progress). False when the track isn't a Mosaic.</summary>@@ -438,6 +440,9 @@ public interface IAudioEngine : IDisposablelong MosaicZoneSampleId(int trackId, int zone);/// <summary>UI editing channel for the track's instrument (e.g. Rhythm step patterns).</summary>void InstrumentAction(int trackId, int id, int iarg, float farg);+ /// <summary>Loads a state blob into the track's instrument and records what it changed in the+ /// instrument's edit state (a Nota Twin's patterns) as an undo step. False when not applied.</summary>+ bool SetInstrumentStateUndoable(int trackId, byte[] data);/// <summary>Loads a sample file into a Nota Grain track (kind 10). True on success.</summary>bool SetTrackGrainSample(int trackId, string path, int rootNote = 60);/// <summary>Sets a Nota Grain's root note — the key that plays the sample at its own pitch.</summary>@@ -758,6 +763,9 @@ public interface IAudioEngine : IDisposableint RackChainInstrumentVoiceCount(int trackId, int chain);int RackChainInstrumentHeldNotes(int trackId, int chain, int[] outNotes);void RackChainInstrumentAction(int trackId, int chain, int id, int iarg, float farg);+ bool RackSetChainInstrumentStateUndoable(int trackId, int chain, byte[] data);+ /// <summary>After param writes to a chain instrument: one undo step from <paramref name="before"/> (its state read first) to now.</summary>+ bool RackChainInstrumentRecordStateUndo(int trackId, int chain, byte[] before);/// <summary>Built-in Sampler settings for a chain instrument. False if it isn't a Sampler.</summary>bool RackChainSamplerInfo(int trackId, int chain, out NotaSamplerInfo info);/// <summary>Sets a chain Sampler's root note (lock-free). False if the chain isn't a Sampler.</summary>@@ -924,6 +932,8 @@ public interface IAudioEngine : IDisposableint RackDevChainInstrumentVoiceCount(int trackId, int deviceIndex, int chain);int RackDevChainInstrumentHeldNotes(int trackId, int deviceIndex, int chain, int[] outNotes);void RackDevChainInstrumentAction(int trackId, int deviceIndex, int chain, int id, int iarg, float farg);+ bool RackDevSetChainInstrumentStateUndoable(int trackId, int deviceIndex, int chain, byte[] data);+ bool RackDevChainInstrumentRecordStateUndo(int trackId, int deviceIndex, int chain, byte[] before);void RackDevOpenChainInstrumentEditor(int trackId, int deviceIndex, int chain);string RackDevChainInstrumentPluginId(int trackId, int deviceIndex, int chain);byte[] RackDevGetChainInstrumentState(int trackId, int deviceIndex, int chain);diff --git a/src/managed/Nota.Application/Engine/IAuditionRig.cs b/src/managed/Nota.Application/Engine/IAuditionRig.csindex 0e3705bf..bbe7f62b 100644--- a/src/managed/Nota.Application/Engine/IAuditionRig.cs+++ b/src/managed/Nota.Application/Engine/IAuditionRig.cs@@ -28,6 +28,8 @@ public interface IAuditionRig : IDisposablebool SetSamplerSample(string? path, int rootNote = 60);/// <summary>Nota Mosaic's program (MosaicProgram text); returns once its samples are loaded.</summary>bool SetMosaicProgram(string text);+ /// <summary>The instrument's state blob after its params (a Nota Twin preset's patterns).</summary>+ bool InstrumentState(byte[] data);/// <summary>Effect source: the first <paramref name="maxSeconds"/> of an audio file.</summary>bool SetSourceFile(string path, double maxSeconds);/// <summary>A fresh rig at the same rate, to render one part of a demo track.</summary>diff --git a/src/managed/Nota.Application/Engine/RackEngineProxies.cs b/src/managed/Nota.Application/Engine/RackEngineProxies.csindex 06b5ea69..4c8fb967 100644--- a/src/managed/Nota.Application/Engine/RackEngineProxies.cs+++ b/src/managed/Nota.Application/Engine/RackEngineProxies.cs@@ -21,6 +21,9 @@ public class RackChainEngineProxy : DispatchProxy{public IAudioEngine Inner = null!;public int Chain;+ // Open gestures on the chain instrument's params: their own (negative) handles.+ private readonly Dictionary<int, (int Track, byte[] Before, int Inner)> _gestures = new();+ private int _nextGesture;public static IAudioEngine Create(IAudioEngine inner, int chain){@@ -46,6 +49,35 @@ public class RackChainEngineProxy : DispatchProxycase nameof(IAudioEngine.InstrumentVoiceCount): return Inner.RackChainInstrumentVoiceCount((int)args![0]!, Chain);case nameof(IAudioEngine.InstrumentHeldNotes): return Inner.RackChainInstrumentHeldNotes((int)args![0]!, Chain, (int[])args![1]!);case nameof(IAudioEngine.InstrumentAction): Inner.RackChainInstrumentAction((int)args![0]!, Chain, (int)args![1]!, (int)args![2]!, (float)args![3]!); return null;+ // The instrument's state blob (a Nota Twin's patterns) is the chain instrument's, not the rack's.+ case nameof(IAudioEngine.GetPluginState) when (int)args![1]! == -1:+ return Inner.RackGetChainInstrumentState((int)args[0]!, Chain);+ case nameof(IAudioEngine.SetPluginState) when (int)args![1]! == -1:+ Inner.RackSetChainInstrumentStateUndoable((int)args[0]!, Chain, (byte[])args[2]!); return null;+ case nameof(IAudioEngine.SetInstrumentStateUndoable):+ return Inner.RackSetChainInstrumentStateUndoable((int)args![0]!, Chain, (byte[])args[1]!);+ // A gesture over the instrument's params (a Twin side / part copy, a preset): they have no+ // undo target in a chain, so the chain instrument's state before it and after it make the+ // step; any other target (the preset tag) keeps its own gesture.+ case nameof(IAudioEngine.BeginMixGesture):+ {+ var targets = (MixTarget[])args![0]!;+ var mine = Array.FindAll(targets, t => t.Kind == MixKind.PluginParam && t.DeviceIndex == -1);+ if (mine.Length == 0) return Inner.BeginMixGesture(targets);+ var rest = Array.FindAll(targets, t => !(t.Kind == MixKind.PluginParam && t.DeviceIndex == -1));+ int inner = rest.Length > 0 ? Inner.BeginMixGesture(rest) : -1;+ int handle = --_nextGesture;+ _gestures[handle] = (mine[0].TrackId, Inner.RackGetChainInstrumentState(mine[0].TrackId, Chain), inner);+ return handle;+ }+ case nameof(IAudioEngine.EndMixGesture):+ {+ int handle = (int)args![0]!;+ if (!_gestures.Remove(handle, out var g)) { Inner.EndMixGesture(handle); return null; }+ if (g.Before.Length > 0) Inner.RackChainInstrumentRecordStateUndo(g.Track, Chain, g.Before);+ if (g.Inner >= 0) Inner.EndMixGesture(g.Inner);+ return null;+ }// Nota Mosaic in a chain (specs/041). Through Inner's rack address −1, which a// NestedRackEngineProxy under it turns into its nested Drum Rack (a Mosaic pad).// A factory Nota Grain preset loads its source sample into the chain's Grain.diff --git a/src/managed/Nota.Application/Localization/en.json b/src/managed/Nota.Application/Localization/en.jsonindex e2a9c088..7b550503 100644--- a/src/managed/Nota.Application/Localization/en.json+++ b/src/managed/Nota.Application/Localization/en.json@@ -1672,6 +1672,62 @@"device.synth.cycles_unison": "{0} · {1} cycles · unison {2}","device.synth.filter_off_the_oscillator_goes": "Filter off — the oscillator goes straight to the amplifier","device.synth.vel_vol_off": "Vel → Vol off",+ "device.twin.arp_hint": "Hold a chord to play it, transport running or not; Hold keeps it going.",+ "device.twin.arpeggio_order": "Arpeggio order",+ "device.twin.clear_the_lane": "Clear the lane",+ "device.twin.click_a_step": "click a step",+ "device.twin.copy_lower_to_upper": "Copy Lower → Upper",+ "device.twin.copy_or_swap_the_parts": "Copy or swap the parts, or load a preset into one",+ "device.twin.copy_side_a_onto_side_b": "Copy side A onto side B",+ "device.twin.copy_side_b_onto_side_a": "Copy side B onto side A",+ "device.twin.copy_upper_to_lower": "Copy Upper → Lower",+ "device.twin.detune_works_in_unison": "Detune works in Unison.",+ "device.twin.edit": "Edit",+ "device.twin.glide_from_step_to_step": "Glide from step to step instead of jumping",+ "device.twin.learn": "Learn",+ "device.twin.load_into_lower": "Load into Lower",+ "device.twin.load_into_upper": "Load into Upper",+ "device.twin.macros_are_sources_in_the_matrix": "Macros are sources in the matrix.",+ "device.twin.make_the_selected_step_a_rest": "Make the selected step a rest",+ "device.twin.matrix_corner": "Source → dest",+ "device.twin.matrix_full_64_routes": "Matrix full (64 routes)",+ "device.twin.matrix_hint": "Drag a cell for side {0}'s depth \u00b7 double-click removes \u00b7 click a name for another",+ "device.twin.no_target": "No target",+ "device.twin.not_a_nota_twin": "Not a Nota Twin.",+ "device.twin.off_bypasses_all_three": "Off bypasses all three, to use Nota's effect devices instead.",+ "device.twin.one_sound_two_layered_or_split": "One sound, two layered on every key, or two split across the keyboard",+ "device.twin.pad_hint": "X → multimode cutoff · Y → morph · hold for Z → vibrato",+ "device.twin.pad_hint_short": "X cutoff · Y morph · Z vibrato",+ "device.twin.pattern_length": "Pattern length",+ "device.twin.pitch_bend_range_in_semitones": "Pitch-bend range in semitones",+ "device.twin.play_a_key_it_becomes_the_split": "Play a key: it becomes the first key of the Upper part",+ "device.twin.rec_motion": "Rec motion",+ "device.twin.record_the_lane": "Record the lane: each step takes the target's value as the pattern passes it",+ "device.twin.rest": "Rest",+ "device.twin.routes_off_the_grid": { "one": "{0} route off the grid", "other": "{0} routes off the grid" },+ "device.twin.seq_empty": "The pattern is empty: switch Record on and play chords, or load a Sequences preset.",+ "device.twin.seq_hint": "Hold a key to play it — or start the transport. Click a step to edit.",+ "device.twin.seq_turn_on": "Switch the sequencer On, then hold a key or start the transport.",+ "device.twin.slope_in_db_per_octave": "Slope in dB per octave",+ "device.twin.step_n_text": "step {0}: {1}",+ "device.twin.step_rate": "Step rate",+ "device.twin.step_record_play_a_chord": "Step record: play a chord, lift it, and it fills the next step",+ "device.twin.swap": "Swap",+ "device.twin.swap_parts": "Swap parts",+ "device.twin.swap_sides_a_and_b": "Swap sides A and B",+ "device.twin.the_morph_as_it_sounds_now": "The morph as it sounds now: the part, and each sounding voice",+ "device.twin.the_part_every_tab_edits": "The part every tab edits",+ "device.twin.the_part_the_sequencer_plays": "The part the sequencer or arpeggiator plays",+ "device.twin.the_pattern_that_plays_and_you_edit": "The pattern that plays and that you edit (switches at the end of the running one)",+ "device.twin.the_side_the_knobs_edit": "The side the knobs edit",+ "device.twin.to_clip": "To clip",+ "device.twin.to_clip_in_rack": "To clip: a Twin on a rack chain can't write its pattern to a clip \u2014 the clip would play every chain of the rack.",+ "device.twin.to_clip_layer_one_part": "To clip: in Layer a clip plays both parts — set the sequencer's part to Both, or play the pattern as it is.",+ "device.twin.to_clip_split_both_parts": "To clip: in Split a clip's notes play one part each, by the split key — pick the sequencer's part first.",+ "device.twin.to_clip_split_other_side": "To clip: some of the pattern's notes are on the other side of the split key from the part the sequencer plays.",+ "device.twin.unknown_part": "Unknown part.",+ "device.twin.what_this_motion_lane_sets": "What this motion lane sets, step by step (on the side being edited)",+ "device.twin.write_this_pattern_as_a_midi_clip": "Write this pattern as a MIDI clip at the playhead's bar and switch the sequencer off","device.utility.bass_mono_off": "bass mono off","device.utility.both_phases_inverted": "both phases inverted","device.utility.channel_stereo_left_or_right": "Channel — Stereo; Left or Right on both sides; Swap the sides",@@ -2854,6 +2910,7 @@"palette.devices.modelled_electric_piano_tine_suitcase": "Modelled electric piano — tine, suitcase, reed and clav with tremolo, phaser and cabinet.","palette.devices.mono_synth": "mono synth","palette.devices.monophonic_analog_style_synth_for": "Monophonic analog-style synth for fat basses and leads.",+ "palette.devices.morphing_poly": "morphing poly","palette.devices.multi_stage_phaser": "Multi-stage phaser.","palette.devices.multiband_dynamics": "multiband dynamics","palette.devices.multisample": "multisample",@@ -2887,6 +2944,7 @@"palette.devices.three_band_dj_style_eq": "Three-band DJ-style EQ with kills.","palette.devices.three_band_upward_and_downward": "Three-band upward and downward compression — OTT-style density.","palette.devices.turns_single_notes_into_chords": "Turns single notes into chords.",+ "palette.devices.twelve_voice_analog_poly_whose_every": "Twelve-voice analog poly whose every sound morphs between two sides — two filters, deep modulation, expression.","palette.devices.two_oscillator_analog_style_synth": "Two-oscillator analog-style synth with drive and a unison stack — pads, basses, acid lines and leads.","palette.devices.vector_morph_synth": "vector-morph synth","palette.devices.vector_synth_morphing_between_sources": "Vector synth morphing between sources — moving pads and textures.",diff --git a/src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.cs b/src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.csindex 0680a1d0..a5fcbb49 100644--- a/src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.cs+++ b/src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.cs@@ -79,6 +79,9 @@ public static class BuiltinDeviceCatalognew("Nota Consort", I, 15, Loc.T("palette.devices.paraphonic_synth"), D("synth.subtractive", "paraphonic string-machine","lush vintage warm", "strings pad choir", "", "", "synthwave",Loc.T("palette.devices.paraphonic_ensemble_synth_string_machines"))),+ new("Nota Twin", I, 18, Loc.T("palette.devices.morphing_poly"), D("synth.subtractive", "polysynth poly morph morphing analog two-filter steiner ladder split layer expressive mpe",+ "lush aggressive warm evolving", "pad keys lead brass bass", "", "", "synthwave cinematic",+ Loc.T("palette.devices.twelve_voice_analog_poly_whose_every"))),new("Nota Keys", I, 16, Loc.T("palette.devices.electric_piano"), D("synth.physical", "epiano e-piano rhodes wurlitzer wurli clavinet clav tine reed suitcase","warm vintage", "keys", "", "", "jazz funk",Loc.T("palette.devices.modelled_electric_piano_tine_suitcase"))),diff --git a/src/managed/Nota.Application/Palette/DeviceCategories.cs b/src/managed/Nota.Application/Palette/DeviceCategories.csindex 83b71013..de474c83 100644--- a/src/managed/Nota.Application/Palette/DeviceCategories.cs+++ b/src/managed/Nota.Application/Palette/DeviceCategories.cs@@ -20,7 +20,7 @@ public static class DeviceCategoriesprivate static readonly Category[] Instruments ={- new("Synths", ["Nota Volt", "Nota Monolith", "Nota Pentad", "Nota Consort",+ new("Synths", ["Nota Volt", "Nota Monolith", "Nota Pentad", "Nota Consort", "Nota Twin","Nota Operator", "Nota Aurora", "Nota Flux", "Nota Pendulum"]),new("Keys & physical", ["Nota Keys", "Nota Physical"]),new("Drums", ["Nota Rhythm", "Nota Drum Rack"]),diff --git a/src/managed/Nota.Application/Palette/PresetDescriptors.cs b/src/managed/Nota.Application/Palette/PresetDescriptors.csindex 45d49594..15440b73 100644--- a/src/managed/Nota.Application/Palette/PresetDescriptors.cs+++ b/src/managed/Nota.Application/Palette/PresetDescriptors.cs@@ -22,6 +22,7 @@ public static class PresetDescriptors["growl & wobble"] = new() { Sound = ["bass"], Character = ["aggressive"], Genre = ["dubstep"] },["electric"] = new() { Sound = ["bass"], Character = ["punchy"] },["sequences"] = new() { Sound = ["seq"] },+ ["morph"] = new() { Character = ["evolving"] }, // Nota Twin: two sounds and the way between them["reactive"] = new() { Character = ["evolving"] },["winds & bowed"] = new() { Sound = ["strings", "brass"] },["basics"] = new() { Character = ["clean"] },diff --git a/src/managed/Nota.Application/Ports/IFactoryPresets.cs b/src/managed/Nota.Application/Ports/IFactoryPresets.csindex 1180e262..5dc514af 100644--- a/src/managed/Nota.Application/Ports/IFactoryPresets.cs+++ b/src/managed/Nota.Application/Ports/IFactoryPresets.cs@@ -33,4 +33,8 @@ public interface IFactoryPresets/// parameter at its default (deviceIndex -1 = the track's instrument). The card size and a/// loaded sample stay as they are. Returns "" on success or a user-facing warning.</summary>string ResetInPlace(IAudioEngine engine, int trackId, int deviceIndex, bool midiEffect);++ /// <summary>A built-in instrument preset's params by id (null when the id is unknown or the+ /// preset names none) — for loading part of a preset, e.g. one Nota Twin part (specs/055).</summary>+ IReadOnlyDictionary<string, float>? InstrumentParams(string id) => null;}diff --git a/src/managed/Nota.Application/Ports/IPresetStore.cs b/src/managed/Nota.Application/Ports/IPresetStore.csindex 7fea0faa..cae701e2 100644--- a/src/managed/Nota.Application/Ports/IPresetStore.cs+++ b/src/managed/Nota.Application/Ports/IPresetStore.cs@@ -21,6 +21,11 @@ public interface IPresetStore/// plug-in). Null when the file can't be read.</summary>(string Type, int BuiltinKind)? Describe(string path);+ /// <summary>A built-in instrument preset file's params by id (null when the file can't be+ /// read, isn't a built-in instrument preset or names none) — for loading part of a preset,+ /// e.g. one Nota Twin part (specs/055).</summary>+ IReadOnlyDictionary<string, float>? InstrumentParams(string path) => null;+/// <summary>Applies a preset file to a device that already matches it, in place/// (<paramref name="deviceIndex"/> −1 = the instrument, else the effect or MIDI effect at that/// index). Returns a warning ("" = clean).</summary>diff --git a/src/managed/Nota.Application/Twin/TwinMatrix.cs b/src/managed/Nota.Application/Twin/TwinMatrix.csnew file mode 100644index 00000000..72488a6e--- /dev/null+++ b/src/managed/Nota.Application/Twin/TwinMatrix.cs@@ -0,0 +1,124 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Twin's modulation matrix from the app's side (specs/055 US4): the source and+// destination tables (mirrors of TwinMod.h / TwinMod.cpp — append-only there, so append here+// too; the smoke test checks every name against the engine), and route edits as single undo+// steps. A slot is four params: "<part>.mN.src", "<part>.mN.dst" (indices / 63 and / 255) and+// a depth per side, "<part>.<a|b>.mNamt" (bipolar, 0.5 = none).++using System;+using System.Collections.Generic;++namespace Nota.Application.Twin;++public static class TwinMatrix+{+ public const int Kind = 18;+ public const int Slots = 64;+ public const int SrcScale = 63, DstScale = 255;++ public static readonly string[] Sources =+ {+ "None", "LFO 1", "LFO 2", "LFO 3", "Filter env", "Amp env", "Mod env", "Velocity", "Release velocity", "Key",+ "Pressure", "Slide", "Bend", "Mod wheel", "Pitch wheel", "Pad X", "Pad Y", "Pad Z", "Random",+ "Macro 1", "Macro 2", "Macro 3", "Macro 4", "Macro 5", "Macro 6", "Macro 7", "Macro 8", "Seq gate", "Seq step",+ };++ // Destinations: six virtual ones, then side params by id (TwinMod.cpp kSideDsts order).+ private static readonly string[] Virtual = { "None", "Morph", "Pitch", "Osc 1 pitch", "Osc 2 pitch", "Vibrato" };+ public static readonly string[] SideDestinationIds =+ {+ "o1wave", "o1pw", "o1metal", "o1fine", "o1level", "o1bal", "o2wave", "o2pw", "o2metal", "o2fine", "o2level",+ "o2bal", "fm21", "fmfilt", "noiselevel", "noisecolor", "noisebal", "mmcut", "mmres", "mmmode", "mmkey", "mmenv",+ "ldcut", "ldres", "ldkey", "ldenv", "route", "brute", "drive", "fenva", "fenvd", "fenvs", "fenvr", "fenvvel",+ "fenvcurve", "aenva", "aenvd", "aenvs", "aenvr", "aenvvel", "aenvcurve", "menvdly", "menva", "menvd", "menvs",+ "menvr", "menvvel", "lfo1rate", "lfo1fade", "lfo1amt", "lfo2rate", "lfo2fade", "lfo2amt", "lfo3rate", "lfo3fade",+ "lfo3amt", "lfo3sym", "lfo3curve", "vibamt", "drift", "unidetune", "spread", "modfxrate", "modfxdepth",+ "modfxmix", "dlytime", "dlyfb", "dlymix", "revsize", "revdamp", "revmix",+ };+ public static int DestinationCount => Virtual.Length + SideDestinationIds.Length;+ public static int DestinationOfSide(string id) => Array.IndexOf(SideDestinationIds, id) is var i and >= 0 ? Virtual.Length + i : 0;++ /// <summary>A destination's name: "Morph", or the side param's own ("Ladder Cutoff"), read+ /// from the engine so it never drifts from the param table.</summary>+ public static string DestinationName(IAudioEngine e, int trackId, int dst)+ {+ if (dst >= 0 && dst < Virtual.Length) return Virtual[dst];+ if (dst >= DestinationCount) return "";+ string name = e.PluginParamName(trackId, -1, Index(e, trackId, "lo.a." + SideDestinationIds[dst - Virtual.Length]));+ int dot = name.IndexOf(" · ", StringComparison.Ordinal);+ return dot >= 0 ? name[(dot + 3)..] : name;+ }++ /// <summary>The group a destination sits in for menus ("Osc1", "Ladder"…; "" for the virtual ones).</summary>+ public static string DestinationGroup(IAudioEngine e, int trackId, int dst)+ {+ string n = DestinationName(e, trackId, dst);+ int sp = dst < Virtual.Length ? -1 : n.LastIndexOf(' ');+ return sp > 0 ? n[..sp] : "";+ }++ public readonly record struct Route(int Slot, int Source, int Destination, float DepthA, float DepthB);++ /// <summary>The part's slots that hold a source and a destination.</summary>+ public static List<Route> Routes(IAudioEngine e, int trackId, string part = "lo")+ {+ var list = new List<Route>();+ var at = IndexMap(e, trackId);+ for (int r = 1; r <= Slots; r++)+ {+ int src = Step(e.PluginParamGet(trackId, -1, at[$"{part}.m{r}.src"]), SrcScale);+ int dst = Step(e.PluginParamGet(trackId, -1, at[$"{part}.m{r}.dst"]), DstScale);+ if (src == 0 || dst == 0) continue;+ list.Add(new Route(r, src, dst, Bip(e.PluginParamGet(trackId, -1, at[$"{part}.a.m{r}amt"])),+ Bip(e.PluginParamGet(trackId, -1, at[$"{part}.b.m{r}amt"]))));+ }+ return list;+ }++ /// <summary>Puts a route in the first free slot (or `slot`), one undo step. Returns the slot+ /// (1..64), or −1 when every slot is taken — the matrix is full.</summary>+ public static int Add(IAudioEngine e, int trackId, int source, int destination, float depthA, float depthB, string part = "lo", int slot = 0)+ {+ var at = IndexMap(e, trackId);+ if (slot <= 0)+ for (int r = 1; r <= Slots && slot <= 0; r++)+ if (Step(e.PluginParamGet(trackId, -1, at[$"{part}.m{r}.src"]), SrcScale) == 0+ || Step(e.PluginParamGet(trackId, -1, at[$"{part}.m{r}.dst"]), DstScale) == 0) slot = r;+ if (slot <= 0 || slot > Slots) return -1;+ Write(e, trackId, at, part, slot, source, destination, depthA, depthB);+ return slot;+ }++ /// <summary>Empties a slot (source, destination, both depths), one undo step.</summary>+ public static void Remove(IAudioEngine e, int trackId, int slot, string part = "lo")+ => Write(e, trackId, IndexMap(e, trackId), part, slot, 0, 0, 0f, 0f);++ private static void Write(IAudioEngine e, int trackId, Dictionary<string, int> at, string part, int slot, int src, int dst, float da, float db)+ {+ var ids = new[] { $"{part}.m{slot}.src", $"{part}.m{slot}.dst", $"{part}.a.m{slot}amt", $"{part}.b.m{slot}amt" };+ var vals = new[] { src / (float)SrcScale, dst / (float)DstScale, 0.5f + 0.5f * Math.Clamp(da, -1f, 1f), 0.5f + 0.5f * Math.Clamp(db, -1f, 1f) };+ var targets = new MixTarget[ids.Length];+ for (int k = 0; k < ids.Length; k++) targets[k] = MixTarget.PluginParam(trackId, -1, at[ids[k]]);+ int g = e.BeginMixGesture(targets);+ for (int k = 0; k < ids.Length; k++) e.PluginParamSet(trackId, -1, at[ids[k]], vals[k]);+ e.EndMixGesture(g);+ }++ private static int Step(float v, int scale) => (int)Math.Round(Math.Clamp(v, 0f, 1f) * scale);+ private static float Bip(float v) => (v - 0.5f) * 2f;+ private static int Index(IAudioEngine e, int trackId, string id)+ {+ int n = e.PluginParamCount(trackId, -1);+ for (int i = 0; i < n; i++) if (e.PluginParamId(trackId, -1, i) == id) return i;+ return -1;+ }+ private static Dictionary<string, int> IndexMap(IAudioEngine e, int trackId)+ {+ int n = e.PluginParamCount(trackId, -1);+ var m = new Dictionary<string, int>(n);+ for (int i = 0; i < n; i++) m[e.PluginParamId(trackId, -1, i)] = i;+ return m;+ }+}diff --git a/src/managed/Nota.Application/Twin/TwinParts.cs b/src/managed/Nota.Application/Twin/TwinParts.csnew file mode 100644index 00000000..98f58520--- /dev/null+++ b/src/managed/Nota.Application/Twin/TwinParts.cs@@ -0,0 +1,70 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Twin's part edits (specs/055 FR-075, US9-4): copy one part onto the other, swap them, or+// load a preset's sound into one part. A part is every param under "lo." or "up." — both sides,+// the matrix, the effects, the voice settings — so an edit remaps ids between the two prefixes+// and writes them as one undo step (TwinSides.Write). The patch-wide params (mode, split key,+// share, voices, pad, sequencer) stay, except that loading into Upper of a Single patch turns+// it to Layer, with the current sound as Lower.++using System.Collections.Generic;+using Nota.Application.Localization;++namespace Nota.Application.Twin;++public static class TwinParts+{+ public enum Edit { CopyLowerToUpper, CopyUpperToLower, Swap }++ private const string Lo = "lo.", Up = "up.";++ private static Dictionary<string, int> Index(IAudioEngine engine, int trackId)+ {+ int n = engine.PluginParamCount(trackId, -1);+ var index = new Dictionary<string, int>(n);+ for (int i = 0; i < n; i++) index[engine.PluginParamId(trackId, -1, i)] = i;+ return index;+ }++ /// <summary>Copies or swaps the parts of the track's Twin. Returns how many params it wrote+ /// (0 = not a Twin).</summary>+ public static int Apply(IAudioEngine engine, int trackId, Edit edit)+ {+ if (engine.TrackInstrumentKind(trackId) != TwinSides.Kind) return 0;+ var index = Index(engine, trackId);+ var writes = new List<(int Index, float Value)>();+ foreach (var (id, il) in index)+ {+ if (!id.StartsWith(Lo, System.StringComparison.Ordinal) || !index.TryGetValue(Up + id[Lo.Length..], out var iu)) continue;+ float vl = engine.PluginParamGet(trackId, -1, il), vu = engine.PluginParamGet(trackId, -1, iu);+ if (edit != Edit.CopyUpperToLower) writes.Add((iu, vl));+ if (edit != Edit.CopyLowerToUpper) writes.Add((il, vu));+ }+ if (writes.Count == 0) return 0;+ TwinSides.Write(engine, trackId, writes);+ return writes.Count;+ }++ /// <summary>Loads a Twin preset's sound — its Lower part, by param id — into <paramref name="part"/>+ /// ("lo" / "up"); a param the preset doesn't name goes to its default. Loading into Upper of a+ /// Single patch switches it to Layer. One undo step; returns "" or a user-facing warning.</summary>+ public static string LoadIntoPart(IAudioEngine engine, int trackId, IReadOnlyDictionary<string, float> preset, string part)+ {+ if (engine.TrackInstrumentKind(trackId) != TwinSides.Kind) return Loc.T("device.twin.not_a_nota_twin");+ if (part is not ("lo" or "up")) return Loc.T("device.twin.unknown_part");+ var index = Index(engine, trackId);+ string to = part + ".";+ var writes = new List<(int Index, float Value)>();+ foreach (var (id, ti) in index)+ {+ if (!id.StartsWith(to, System.StringComparison.Ordinal)) continue;+ string src = Lo + id[to.Length..];+ writes.Add((ti, preset.TryGetValue(src, out var v) ? v : engine.InstrumentParamDefault(trackId, ti)));+ }+ if (part == "up" && index.TryGetValue("mode", out var mi) && engine.PluginParamGet(trackId, -1, mi) < 0.25f)+ writes.Add((mi, 0.5f));+ TwinSides.Write(engine, trackId, writes);+ return "";+ }+}diff --git a/src/managed/Nota.Application/Twin/TwinPatterns.cs b/src/managed/Nota.Application/Twin/TwinPatterns.csnew file mode 100644index 00000000..7b92e3a4--- /dev/null+++ b/src/managed/Nota.Application/Twin/TwinPatterns.cs@@ -0,0 +1,389 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Twin's sequencer patterns from the app's side (specs/055 US8): the pattern block of the+// instrument's state (a mirror of TwinSeq.cpp's layout), a text form of a pattern's steps for+// presets and MCP, and "To clip" — a pattern written out as an ordinary MIDI clip, its motion+// lanes as automation.+//+// Text form, one row per step: notes separated by spaces, then optional ":velocity" (1..127) and+// ":gate" ("50%" or "tie"); "." is a rest. E.g. "C3 E3 G3:100:50%", ".", "A2:90:tie".++using System;+using System.Collections.Generic;+using System.Globalization;+using System.Linq;++namespace Nota.Application.Twin;++public static class TwinPatterns+{+ public const int Patterns = 8, Steps = 64, StepNotes = 6, Lanes = 4;+ public const int GateTie = 101;+ public const ushort MotionUnset = 0xFFFF;+ private const uint Magic = 0x31505754; // "TWP1"+ private const uint StateMagic = 0x314E5754; // "TWN1"++ public sealed class Step+ {+ public List<int> Notes = new();+ public int Velocity = 100;+ public int Gate = 50; // 1..100 %, GateTie+ public bool IsRest => Notes.Count == 0;+ }+ public sealed class Lane+ {+ public int Target = -1; // param index+ public bool Smooth;+ public ushort[] Values = Enumerable.Repeat(MotionUnset, Steps).ToArray();+ }+ public sealed class Pattern+ {+ public int Length = 16;+ public Step[] Steps = Enumerable.Range(0, TwinPatterns.Steps).Select(_ => new Step()).ToArray();+ public Lane[] Lanes = Enumerable.Range(0, TwinPatterns.Lanes).Select(_ => new Lane()).ToArray();+ }++ // ---- the pattern block ------------------------------------------------------------------++ /// <summary>The patterns inside a Twin state blob ("TWN1"), or null when it carries none.</summary>+ public static Pattern[]? FromState(byte[] state)+ {+ if (state.Length < 8 || BitConverter.ToUInt32(state, 0) != StateMagic) return null;+ int at = 8 + 4 * (int)BitConverter.ToUInt32(state, 4);+ if (state.Length < at + 4) return null;+ int bytes = (int)BitConverter.ToUInt32(state, at);+ return state.Length >= at + 4 + bytes ? Decode(state[(at + 4)..(at + 4 + bytes)]) : null;+ }++ public static Pattern[]? Decode(byte[] b)+ {+ if (b.Length < 4 || BitConverter.ToUInt32(b, 0) != Magic) return null;+ int p = 4;+ int U8() => p < b.Length ? b[p++] : 0;+ ushort U16() { int lo = U8(), hi = U8(); return (ushort)(lo | hi << 8); }+ var set = new Pattern[Patterns];+ for (int i = 0; i < Patterns; i++)+ {+ var pat = new Pattern { Length = Math.Clamp(U8(), 1, Steps) };+ foreach (var s in pat.Steps)+ {+ int n = Math.Min((int)U8(), StepNotes);+ var notes = new int[StepNotes];+ for (int k = 0; k < StepNotes; k++) notes[k] = U8();+ s.Notes = notes.Take(n).ToList();+ s.Velocity = U8();+ s.Gate = U8();+ }+ foreach (var l in pat.Lanes)+ {+ l.Target = (short)U16();+ l.Smooth = U8() != 0;+ for (int k = 0; k < Steps; k++) l.Values[k] = U16();+ }+ set[i] = pat;+ }+ return p <= b.Length ? set : null;+ }++ public static byte[] Encode(IReadOnlyList<Pattern> set)+ {+ var b = new List<byte>();+ void U8(int v) => b.Add((byte)v);+ void U16(int v) { b.Add((byte)v); b.Add((byte)(v >> 8)); }+ b.AddRange(BitConverter.GetBytes(Magic));+ for (int i = 0; i < Patterns; i++)+ {+ var pat = i < set.Count ? set[i] : new Pattern();+ U8(pat.Length);+ foreach (var s in pat.Steps)+ {+ U8(s.Notes.Count);+ for (int k = 0; k < StepNotes; k++) U8(k < s.Notes.Count ? s.Notes[k] : 0);+ U8(Math.Clamp(s.Velocity, 1, 127));+ U8(Math.Clamp(s.Gate, 1, GateTie));+ }+ foreach (var l in pat.Lanes)+ {+ U16(l.Target);+ U8(l.Smooth ? 1 : 0);+ foreach (var v in l.Values) U16(v);+ }+ }+ return b.ToArray();+ }++ /// <summary>A Twin state blob that carries only patterns (no params): what a preset stores.</summary>+ public static byte[] StateWithPatterns(IReadOnlyList<Pattern> set)+ {+ var block = Encode(set);+ var b = new List<byte>();+ b.AddRange(BitConverter.GetBytes(StateMagic));+ b.AddRange(BitConverter.GetBytes(0u));+ b.AddRange(BitConverter.GetBytes((uint)block.Length));+ b.AddRange(block);+ return b.ToArray();+ }++ // ---- text ----------------------------------------------------------------------------------++ private static readonly string[] Names = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };+ public static string NoteName(int n) => $"{Names[n % 12]}{n / 12 - 1}";+ public static int ParseNote(string s)+ {+ s = s.Trim();+ int i = 1;+ if (s.Length > 1 && (s[1] == '#' || s[1] == 'b')) i = 2;+ int pc = Array.FindIndex(Names, x => string.Equals(x, s[..1], StringComparison.OrdinalIgnoreCase));+ if (pc < 0 || !int.TryParse(s[i..], NumberStyles.Integer, CultureInfo.InvariantCulture, out int oct)) return -1;+ if (i == 2) pc += s[1] == '#' ? 1 : -1;+ int n = (oct + 1) * 12 + pc;+ return n is >= 0 and <= 127 ? n : -1;+ }++ public static string StepText(Step s)+ {+ if (s.IsRest) return ".";+ string gate = s.Gate >= GateTie ? "tie" : $"{s.Gate}%";+ return $"{string.Join(' ', s.Notes.Select(NoteName))}:{s.Velocity}:{gate}";+ }++ /// <summary>Parses one row; null and an error message when it can't.</summary>+ public static Step? ParseStep(string row, out string error)+ {+ error = "";+ row = row.Trim();+ var s = new Step();+ if (row == "." || row.Length == 0) return s;+ var parts = row.Split(':');+ foreach (var t in parts[0].Split(' ', StringSplitOptions.RemoveEmptyEntries))+ {+ int n = ParseNote(t);+ if (n < 0) { error = $"note '{t}'"; return null; }+ if (s.Notes.Count < StepNotes && !s.Notes.Contains(n)) s.Notes.Add(n);+ }+ if (parts.Length > 1 && parts[1].Length > 0)+ {+ if (!int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out int v)) { error = $"velocity '{parts[1]}'"; return null; }+ s.Velocity = Math.Clamp(v, 1, 127);+ }+ if (parts.Length > 2 && parts[2].Length > 0)+ {+ string g = parts[2].Trim().TrimEnd('%');+ if (g.Equals("tie", StringComparison.OrdinalIgnoreCase)) s.Gate = GateTie;+ else if (int.TryParse(g, NumberStyles.Integer, CultureInfo.InvariantCulture, out int gv)) s.Gate = Math.Clamp(gv, 1, 100);+ else { error = $"gate '{parts[2]}'"; return null; }+ }+ return s;+ }++ // ---- editing (Twin::Act, contracts/c-abi.md) -------------------------------------------------++ public enum Act+ {+ SelectPattern = 0, SetLength, ClearStep, AddStepNote, RemoveStepNote, SetStepVelocity, SetStepGate,+ StepRecordArm, StepRecordAdvance, ClearPattern, CopyPattern, MotionTarget, MotionMode, MotionSet,+ MotionRecordArm, ClearMotion, StepRecordPoll,+ }++ public static void Do(IAudioEngine e, int trackId, Act a, int iarg = 0, float farg = 0f) => e.InstrumentAction(trackId, (int)a, iarg, farg);++ /// <summary>Replaces a pattern's steps with `rows` (the text form; the length becomes the row+ /// count) — one undo step. Returns "" or what it could not read.</summary>+ public static string WritePattern(IAudioEngine e, int trackId, int pattern, IReadOnlyList<string> rows)+ {+ if (rows.Count is < 1 or > Steps) return $"{rows.Count} rows — a pattern has 1..{Steps}";+ var steps = new List<Step>();+ for (int i = 0; i < rows.Count; i++)+ {+ var st = ParseStep(rows[i], out var err);+ if (st is null) return $"row {i + 1}: {err}";+ steps.Add(st);+ }+ e.BeginUndoGroup();+ try+ {+ Do(e, trackId, Act.SelectPattern, pattern);+ Do(e, trackId, Act.SetLength, steps.Count);+ for (int i = 0; i < steps.Count; i++)+ {+ Do(e, trackId, Act.ClearStep, i);+ foreach (var n in steps[i].Notes) Do(e, trackId, Act.AddStepNote, i << 8 | n, steps[i].Velocity / 127f);+ Do(e, trackId, Act.SetStepVelocity, i, steps[i].Velocity / 127f);+ Do(e, trackId, Act.SetStepGate, i, steps[i].Gate >= GateTie ? 1.01f : steps[i].Gate / 100f);+ }+ }+ finally+ {+ e.EndUndoGroup();+ }+ return "";+ }++ // ---- To clip -------------------------------------------------------------------------------++ private static readonly double[] RateBeats = { 1.0, 0.5, 1.0 / 3.0, 0.25, 1.0 / 6.0, 0.125 };++ /// <summary>Why a pattern can't become a clip that sounds like the sequencer playing it: a clip's+ /// notes reach the parts by the keyboard's rule (Layer: both; Split: by the split key), while the+ /// sequencer plays the parts Sequencer Target names.</summary>+ public enum ClipBlock+ {+ None,+ LayerOnePart, // Layer, the sequencer on one part: a clip would play both+ SplitBothParts, // Split, the sequencer on both parts: a clip would play one per key+ SplitOtherSide, // Split, a note on the other side of the split key from the part it plays+ InRack, // a Twin on a rack chain: the clip would land on the rack's track and play every chain+ }++ /// <summary>Whether <see cref="ToClip"/> can write the pattern (it refuses what it can't reproduce).</summary>+ public static ClipBlock ToClipBlock(IAudioEngine e, int trackId, int pattern)+ {+ if (e.TrackInstrumentKind(trackId) != TwinMatrix.Kind) return ClipBlock.None;+ if (e is RackChainEngineProxy) return ClipBlock.InRack;+ var set = FromState(e.GetPluginState(trackId, -1));+ if (set is null || pattern < 0 || pattern >= Patterns) return ClipBlock.None;+ return Block(set[pattern], ParamReader(e, trackId).G);+ }++ private static (Dictionary<string, int> At, Func<string, float> G) ParamReader(IAudioEngine e, int trackId)+ {+ var at = new Dictionary<string, int>();+ int pc = e.PluginParamCount(trackId, -1);+ for (int i = 0; i < pc; i++) at[e.PluginParamId(trackId, -1, i)] = i;+ return (at, id => e.PluginParamGet(trackId, -1, at[id]));+ }++ private static int StepOf(float v, int n) => Math.Clamp((int)Math.Round(v * (n - 1), MidpointRounding.AwayFromZero), 0, n - 1);++ private static ClipBlock Block(Pattern pat, Func<string, float> G)+ {+ int mode = StepOf(G("mode"), 3); // Single / Layer / Split+ int target = StepOf(G("seq.target"), 3); // Lower / Upper / Both+ if (mode == 1) return target == 2 ? ClipBlock.None : ClipBlock.LayerOnePart;+ if (mode != 2) return ClipBlock.None;+ if (target == 2) return ClipBlock.SplitBothParts;+ int split = (int)Math.Round(G("splitkey") * 127f, MidpointRounding.AwayFromZero);+ for (int k = 0; k < pat.Length; k++)+ foreach (var n in pat.Steps[k].Notes)+ if ((n < split) != (target == 0)) return ClipBlock.SplitOtherSide;+ return ClipBlock.None;+ }++ // Motion points end this far before the next step's onset, so a held value steps there.+ private const double MotionEdge = 1e-4;++ /// <summary>Writes a pattern of the track's Twin as a MIDI clip at `startBeat` (notes, velocities,+ /// gates, ties and the swing) and its motion lanes as automation over the clip, then turns the+ /// sequencer off — one undo step. Automation already on those parameters outside the clip stays.+ /// Returns the clip index, or -1 (also when <see cref="ToClipBlock"/> says the clip couldn't+ /// sound as the sequencer does).</summary>+ public static int ToClip(IAudioEngine e, int trackId, int pattern, double startBeat)+ {+ if (e.TrackInstrumentKind(trackId) != TwinMatrix.Kind) return -1;+ var set = FromState(e.GetPluginState(trackId, -1));+ if (set is null || pattern < 0 || pattern >= Patterns) return -1;+ var pat = set[pattern];+ if (e is RackChainEngineProxy) return -1; // ClipBlock.InRack+ var (at, G) = ParamReader(e, trackId);+ if (Block(pat, G) != ClipBlock.None) return -1;+ int pc = at.Count;+ double sb = RateBeats[StepOf(G("seq.rate"), 6)];+ double swing = G("seq.swing") * 0.5 * sb;+ double On(int k) => k * sb + ((k & 1) == 1 ? swing : 0);++ var notes = new List<NotaNote>();+ for (int k = 0; k < pat.Length; k++)+ {+ var s = pat.Steps[k];+ foreach (var n in s.Notes)+ {+ // A tie runs on through the following steps that hold the same note.+ if (k > 0 && pat.Steps[k - 1].Gate >= GateTie && pat.Steps[k - 1].Notes.Contains(n)) continue;+ int last = k;+ while (pat.Steps[last].Gate >= GateTie && last + 1 < pat.Length && pat.Steps[last + 1].Notes.Contains(n)) last++;+ var end = pat.Steps[last];+ double off = On(last) + (end.Gate >= GateTie ? sb : end.Gate * 0.01 * sb);+ notes.Add(new NotaNote(n, On(k), off - On(k), s.Velocity / 127f));+ }+ }+ // The clip runs to the pattern's end, or on to its last note-off when a swung long note (or a+ // tie on the last step) rings past it, so every note keeps its live length.+ double length = Math.Max(sb, pat.Length * sb);+ foreach (var n in notes) length = Math.Max(length, n.StartBeat + n.LengthBeats);+ e.BeginUndoGroup();+ try+ {+ int clip = e.AddMidiClip(trackId, startBeat, length);+ if (clip < 0) return -1;+ e.SetClipNotes(trackId, clip, notes.ToArray());+ foreach (var lane in pat.Lanes)+ {+ if (lane.Target < 0 || lane.Target >= pc || lane.Values.Take(pat.Length).All(v => v == MotionUnset)) continue;+ int li = e.AddPluginAutomationLane(trackId, -1, e.PluginParamId(trackId, -1, lane.Target));+ if (li < 0) continue;+ float knob = e.PluginParamGet(trackId, -1, lane.Target); // what an empty step plays+ var pts = MotionPoints(pat, lane, sb, On, On(pat.Length), length, knob).Select(p => new AutomationPoint(startBeat + p.Beat, p.Value)).ToList();+ // An existing lane keeps its points before and after the clip.+ double end = startBeat + length;+ var kept = e.GetAutomationPoints(trackId, li).Where(p => p.Beat < startBeat || p.Beat > end);+ e.SetAutomationPoints(trackId, li, kept.Concat(pts).OrderBy(p => p.Beat).ToArray());+ }+ int seqOn = at["seq.on"];+ int g = e.BeginMixGesture(MixTarget.PluginParam(trackId, -1, seqOn)); // undoes with the clip+ e.PluginParamSet(trackId, -1, seqOn, 0f);+ e.EndMixGesture(g);+ return clip;+ }+ finally+ {+ e.EndUndoGroup();+ }+ }++ // A motion lane as the sequencer plays it (Twin::fireStep / updateControl): from each step's+ // onset to the next one's, a stepped lane holds the step's value, and a smooth one glides to the+ // next step's value (the last to the first) over one step length — cut short at the next onset+ // when the swing brings it early, held when it comes late.+ // An empty step lets the knob play (the lane lets go of it): the points hold `knob` there.+ // Past the pattern's end (a last note ringing on), the lane plays what the next pass's first+ // step does: its value, or the knob.+ private static IEnumerable<(double Beat, float Value)> MotionPoints(Pattern pat, Lane lane, double sb,+ Func<int, double> on, double patternEnd, double length, float knob)+ {+ for (int k = 0; k < pat.Length; k++)+ {+ double t0 = on(k), next = k + 1 < pat.Length ? on(k + 1) : Math.Min(patternEnd, length);+ double hold = Math.Max(t0, next - MotionEdge);+ if (lane.Values[k] == MotionUnset)+ {+ yield return (t0, knob);+ yield return (hold, knob);+ continue;+ }+ float v = lane.Values[k] / 65534f;+ yield return (t0, v);+ if (!lane.Smooth)+ {+ yield return (hold, v);+ continue;+ }+ ushort nx = lane.Values[(k + 1) % pat.Length];+ float to = nx == MotionUnset ? v : nx / 65534f;+ double glideEnd = t0 + sb;+ if (glideEnd < hold)+ {+ yield return (glideEnd, to);+ yield return (hold, to);+ }+ else+ yield return (hold, v + (to - v) * (float)((hold - t0) / sb));+ }+ if (length > patternEnd + MotionEdge)+ {+ float first = lane.Values[0] == MotionUnset ? knob : lane.Values[0] / 65534f;+ yield return (patternEnd, first);+ yield return (length, first);+ }+ }+}diff --git a/src/managed/Nota.Application/Twin/TwinSides.cs b/src/managed/Nota.Application/Twin/TwinSides.csnew file mode 100644index 00000000..e9a25574--- /dev/null+++ b/src/managed/Nota.Application/Twin/TwinSides.cs@@ -0,0 +1,71 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Twin's side edits (specs/055 FR-022): copy one morph side onto the other, or swap them.+// Every sound parameter of a part exists as "<part>.a.<name>" and "<part>.b.<name>", so a side+// edit is a batch of plain param writes, recorded by mix gestures inside one undo group, so it+// is one undo step in the engine's history (specs/009, specs/016).++using System.Collections.Generic;++namespace Nota.Application.Twin;++public static class TwinSides+{+ public const int Kind = 18;++ public enum Edit { CopyAToB, CopyBToA, Swap }++ // The engine's limit on one mix gesture (nota_mix_gesture_begin).+ private const int MaxGestureTargets = 64;++ /// <summary>Applies <paramref name="edit"/> to the part ("lo" / "up") of the track's Twin.+ /// Returns how many params it wrote (0 = not a Twin or nothing to do).</summary>+ public static int Apply(IAudioEngine engine, int trackId, Edit edit, string part = "lo")+ {+ if (engine.TrackInstrumentKind(trackId) != Kind) return 0;+ int n = engine.PluginParamCount(trackId, -1);+ var index = new Dictionary<string, int>(n);+ for (int i = 0; i < n; i++) index[engine.PluginParamId(trackId, -1, i)] = i;+ string a = part + ".a.", b = part + ".b.";+ var pairs = new List<(int A, int B)>();+ foreach (var (id, ia) in index)+ if (id.StartsWith(a, System.StringComparison.Ordinal) && index.TryGetValue(b + id[a.Length..], out var ib))+ pairs.Add((ia, ib));+ if (pairs.Count == 0) return 0;++ // The writes, decided up front (a swap reads both sides before touching either).+ var writes = new List<(int Index, float Value)>(pairs.Count * 2);+ foreach (var (ia, ib) in pairs)+ {+ float va = engine.PluginParamGet(trackId, -1, ia), vb = engine.PluginParamGet(trackId, -1, ib);+ if (edit != Edit.CopyBToA) writes.Add((ib, va));+ if (edit != Edit.CopyAToB) writes.Add((ia, vb));+ }+ Write(engine, trackId, writes);+ return edit == Edit.Swap ? pairs.Count * 2 : pairs.Count;+ }++ /// <summary>Writes plugin params as one undo step: mix gestures of at most+ /// MaxGestureTargets values (the engine's limit) inside one undo group.</summary>+ internal static void Write(IAudioEngine engine, int trackId, IReadOnlyList<(int Index, float Value)> writes)+ {+ engine.BeginUndoGroup();+ try+ {+ for (int at = 0; at < writes.Count; at += MaxGestureTargets)+ {+ int count = System.Math.Min(MaxGestureTargets, writes.Count - at);+ var targets = new MixTarget[count];+ for (int k = 0; k < count; k++) targets[k] = MixTarget.PluginParam(trackId, -1, writes[at + k].Index);+ int gesture = engine.BeginMixGesture(targets);+ for (int k = 0; k < count; k++) engine.PluginParamSet(trackId, -1, writes[at + k].Index, writes[at + k].Value);+ engine.EndMixGesture(gesture);+ }+ }+ finally+ {+ engine.EndUndoGroup();+ }+ }+}diff --git a/src/managed/Nota.Infrastructure/Audition/PresetAudition.cs b/src/managed/Nota.Infrastructure/Audition/PresetAudition.csindex 8b347d0b..e287ea88 100644--- a/src/managed/Nota.Infrastructure/Audition/PresetAudition.cs+++ b/src/managed/Nota.Infrastructure/Audition/PresetAudition.cs@@ -98,6 +98,12 @@ public sealed partial class PresetAudition : IPresetAuditionif (!rig.SetInstrument(kind)) return false;foreach (var (id, v) in named)if (!InstrumentView.IsViewParam(id)) rig.InstrumentParam(id, v);+ // A Nota Twin preset's patterns: its sequencer plays them over the phrase.+ if (kind == Nota.Application.Twin.TwinMatrix.Kind && !string.IsNullOrEmpty(doc.StateBase64))+ {+ try { rig.InstrumentState(System.Convert.FromBase64String(doc.StateBase64)); }+ catch (System.FormatException) { }+ }// A Nota Grain factory preset is heard on its own source.if (kind == 10 && !string.IsNullOrEmpty(doc.GrainSource)){@@ -182,7 +188,7 @@ public sealed partial class PresetAudition : IPresetAudition{[0] = "Nota Synth", [1] = "Nota Sampler", [2] = "Nota Physical", [5] = "Nota Aurora", [6] = "Nota Volt",[7] = "Nota Bass", [8] = "Nota Pendulum", [9] = "Nota Operator", [10] = "Nota Grain", [11] = "Nota Flux",- [12] = "Nota Rhythm", [13] = "Nota Monolith", [14] = "Nota Pentad", [15] = "Nota Consort", [16] = "Nota Keys", [17] = "Nota Mosaic",+ [12] = "Nota Rhythm", [13] = "Nota Monolith", [14] = "Nota Pentad", [15] = "Nota Consort", [16] = "Nota Keys", [17] = "Nota Mosaic", [18] = "Nota Twin",};private static readonly Dictionary<int, string> MidiNames = new(){@@ -287,7 +293,7 @@ public sealed partial class PresetAudition : IPresetAuditionbool Has(params string[] words) { foreach (var w in words) if (c.Contains(w)) return true; return false; }if (Has("sequence", "arp", "generative")) return Held;if (Has("bass", "sub", "acid", "growl", "wobble", "808")) return BassRiff;- if (Has("pad", "ambient", "ensemble", "string", "choir", "bowed", "waterfall", "swell")) return Pad;+ if (Has("pad", "ambient", "ensemble", "string", "choir", "bowed", "waterfall", "swell", "morph")) return Pad; // morph: Nota Twin's folder — a held chord lets the morph travelif (Has("texture", "drone", "sweep", " fx", "motion", "noise")) return Texture;if (Has("lead", "brass", "solo", "whistle")) return Lead;if (Has("bell", "mallet", "pluck", "harp", "music box", "percussion", "perc", "marimba", "vibra")) return Pluck;diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Audition.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Audition.csindex 84745100..8d849c12 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Audition.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Audition.cs@@ -48,6 +48,9 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_audition_set_mosaic_program", StringMarshalling = StringMarshalling.Utf8)]internal static partial int AuditionSetMosaicProgram(IntPtr rig, string text);+ [LibraryImport(Lib, EntryPoint = "nota_audition_instrument_state")]+ internal static partial int AuditionInstrumentState(IntPtr rig, byte[] data, int size);+[LibraryImport(Lib, EntryPoint = "nota_audition_add_source_from")]internal static partial int AuditionAddSourceFrom(IntPtr rig, IntPtr part, float gain);diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Rack.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Rack.csindex f51a8ff2..12a743b3 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Rack.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Rack.cs@@ -44,6 +44,12 @@ internal static partial class NativeMethodsinternal static partial int RackChainInstrumentHeldNotes(IntPtr engine, int trackId, int chain, [Out] int[] outNotes, int maxN);[LibraryImport(Lib, EntryPoint = "nota_rack_chain_instrument_action")]internal static partial void RackChainInstrumentAction(IntPtr engine, int trackId, int chain, int id, int iarg, float farg);+ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_instrument_record_state_undo")]+ internal static partial int RackChainInstrumentRecordStateUndo(IntPtr engine, int trackId, int chain, byte[] before, int size);+ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_instrument_record_state_undo")]+ internal static partial int RackDevChainInstrumentRecordStateUndo(IntPtr engine, int trackId, int deviceIndex, int chain, byte[] before, int size);+ [LibraryImport(Lib, EntryPoint = "nota_rack_chain_instrument_set_state_undoable")]+ internal static partial int RackChainInstrumentSetStateUndoable(IntPtr engine, int trackId, int chain, byte[] data, int size);[LibraryImport(Lib, EntryPoint = "nota_rack_chain_sampler_info")]internal static partial int RackChainSamplerInfo(IntPtr engine, int trackId, int chain, out NotaSamplerInfo info);@@ -340,6 +346,9 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_instrument_action")]internal static partial void RackDevChainInstrumentAction(IntPtr engine, int trackId, int deviceIndex, int chain, int id, int iarg, float farg);+ [LibraryImport(Lib, EntryPoint = "nota_rackdev_chain_instrument_set_state_undoable")]+ internal static partial int RackDevChainInstrumentSetStateUndoable(IntPtr engine, int trackId, int deviceIndex, int chain, byte[] data, int size);+[LibraryImport(Lib, EntryPoint = "nota_rackdev_open_chain_instrument_editor")]internal static partial void RackDevOpenChainInstrumentEditor(IntPtr engine, int trackId, int deviceIndex, int chain);diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.csindex 30fdacf3..0abf5e60 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs@@ -440,6 +440,9 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_engine_add_mosaic_track")]internal static partial int AddMosaicTrack(IntPtr engine);+ [LibraryImport(Lib, EntryPoint = "nota_engine_add_twin_track")]+ internal static partial int AddTwinTrack(IntPtr engine);+[LibraryImport(Lib, EntryPoint = "nota_track_mosaic_set_program", StringMarshalling = StringMarshalling.Utf8)]internal static partial int MosaicSetProgram(IntPtr engine, int trackId, string text, int checkpoint);@@ -461,6 +464,9 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_track_instrument_action")]internal static partial void InstrumentAction(IntPtr engine, int trackId, int id, int iarg, float farg);+ [LibraryImport(Lib, EntryPoint = "nota_track_instrument_set_state_undoable")]+ internal static partial int InstrumentSetStateUndoable(IntPtr engine, int trackId, byte[] data, int size);+[LibraryImport(Lib, EntryPoint = "nota_track_set_grain_sample", StringMarshalling = StringMarshalling.Utf8)]internal static partial int SetTrackGrainSample(IntPtr engine, int trackId, string path, int rootNote);diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.csindex fc31914a..f6d48955 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs@@ -132,6 +132,12 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_engine_note_off")]internal static partial NotaResult NoteOff(IntPtr engine, int pitch);+ [LibraryImport(Lib, EntryPoint = "nota_engine_note_off_velocity")]+ internal static partial NotaResult NoteOffVelocity(IntPtr engine, int pitch, float releaseVelocity);++ [LibraryImport(Lib, EntryPoint = "nota_track_note_off_velocity")]+ internal static partial NotaResult TrackNoteOffVelocity(IntPtr engine, int trackId, int pitch, float releaseVelocity);+[LibraryImport(Lib, EntryPoint = "nota_track_note_on")]internal static partial NotaResult TrackNoteOn(IntPtr engine, int trackId, int pitch, float velocity);diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Audition.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Audition.csindex 4ea2d190..2b175fba 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Audition.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Audition.cs@@ -48,6 +48,7 @@ public sealed partial class NotaEnginepublic bool SetSamplerSample(string? path, int rootNote = 60) => NativeMethods.AuditionSetSamplerSample(Handle, path, rootNote) != 0;/// <summary>Nota Mosaic's program; returns once its samples are loaded.</summary>public bool SetMosaicProgram(string text) => NativeMethods.AuditionSetMosaicProgram(Handle, text) != 0;+ public bool InstrumentState(byte[] data) => data.Length > 0 && NativeMethods.AuditionInstrumentState(Handle, data, data.Length) != 0;public bool AddSourceFrom(IAuditionRig part, float gain)=> part is AuditionRig p && NativeMethods.AuditionAddSourceFrom(Handle, p.Handle, gain) != 0;public bool UseCachedSource(string key) => NativeMethods.AuditionUseCachedSource(Handle, key) != 0;diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Rack.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Rack.csindex a4b20363..64648225 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Rack.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Rack.cs@@ -126,6 +126,15 @@ public sealed partial class NotaEnginepublic void RackChainInstrumentAction(int trackId, int chain, int id, int iarg, float farg){ ThrowIfDisposed(); NativeMethods.RackChainInstrumentAction(_handle, trackId, chain, id, iarg, farg); }+ public bool RackSetChainInstrumentStateUndoable(int trackId, int chain, byte[] data)+ { ThrowIfDisposed(); return NativeMethods.RackChainInstrumentSetStateUndoable(_handle, trackId, chain, data, data.Length) != 0; }++ public bool RackChainInstrumentRecordStateUndo(int trackId, int chain, byte[] before)+ { ThrowIfDisposed(); return NativeMethods.RackChainInstrumentRecordStateUndo(_handle, trackId, chain, before, before.Length) != 0; }++ public bool RackDevChainInstrumentRecordStateUndo(int trackId, int deviceIndex, int chain, byte[] before)+ { ThrowIfDisposed(); return NativeMethods.RackDevChainInstrumentRecordStateUndo(_handle, trackId, deviceIndex, chain, before, before.Length) != 0; }+public bool RackChainSamplerInfo(int trackId, int chain, out NotaSamplerInfo info){ ThrowIfDisposed(); return NativeMethods.RackChainSamplerInfo(_handle, trackId, chain, out info) != 0; }@@ -353,6 +362,12 @@ public sealed partial class NotaEngine{ ThrowIfDisposed(); return NativeMethods.RackDevChainInstrumentHeldNotes(_handle, trackId, deviceIndex, chain, outNotes, outNotes.Length); }public void RackDevChainInstrumentAction(int trackId, int deviceIndex, int chain, int id, int iarg, float farg){ ThrowIfDisposed(); NativeMethods.RackDevChainInstrumentAction(_handle, trackId, deviceIndex, chain, id, iarg, farg); }++ public bool RackDevSetChainInstrumentStateUndoable(int trackId, int deviceIndex, int chain, byte[] data)+ {+ ThrowIfDisposed();+ return NativeMethods.RackDevChainInstrumentSetStateUndoable(_handle, trackId, deviceIndex, chain, data, data.Length) != 0;+ }public void RackDevOpenChainInstrumentEditor(int trackId, int deviceIndex, int chain){ ThrowIfDisposed(); NativeMethods.RackDevOpenChainInstrumentEditor(_handle, trackId, deviceIndex, chain); }public string RackDevChainInstrumentPluginId(int trackId, int deviceIndex, int chain)diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.csindex 74993010..927b3e42 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs@@ -945,6 +945,15 @@ public sealed partial class NotaEnginereturn id;}+ /// <summary>Adds an instrument track with the built-in Nota Twin morphing poly. Returns its id.</summary>+ public int AddTwinTrack()+ {+ ThrowIfDisposed();+ var id = NativeMethods.AddTwinTrack(_handle);+ if (id <= 0) throw new NotaEngineException("Failed to add Twin track.");+ return id;+ }+public bool MosaicSetProgram(int trackId, string text, bool undoable = true){ ThrowIfDisposed(); return NativeMethods.MosaicSetProgram(_handle, trackId, text ?? "", undoable ? 1 : 0) != 0; }@@ -984,6 +993,9 @@ public sealed partial class NotaEnginepublic void InstrumentAction(int trackId, int id, int iarg, float farg){ ThrowIfDisposed(); NativeMethods.InstrumentAction(_handle, trackId, id, iarg, farg); }+ public bool SetInstrumentStateUndoable(int trackId, byte[] data)+ { ThrowIfDisposed(); return NativeMethods.InstrumentSetStateUndoable(_handle, trackId, data, data.Length) != 0; }+public bool SetTrackGrainSample(int trackId, string path, int rootNote = 60){ ThrowIfDisposed(); return NativeMethods.SetTrackGrainSample(_handle, trackId, path, rootNote) != 0; }diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.csindex c5e70719..ce377701 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs@@ -140,6 +140,11 @@ public sealed partial class NotaEngine : IAudioEnginepublic void SetTrackArmed(int trackId, bool armed) { ThrowIfDisposed(); Check(NativeMethods.SetTrackArmed(_handle, trackId, armed ? 1 : 0)); }public void NoteOn(int pitch, float velocity) { ThrowIfDisposed(); Check(NativeMethods.NoteOn(_handle, pitch, velocity)); }public void NoteOff(int pitch) { ThrowIfDisposed(); Check(NativeMethods.NoteOff(_handle, pitch)); }+ /// <summary>A live note-off with its release velocity (0..1), as a MIDI note-off carries it.</summary>+ public void NoteOffVelocity(int pitch, float releaseVelocity) { ThrowIfDisposed(); Check(NativeMethods.NoteOffVelocity(_handle, pitch, releaseVelocity)); }+ /// <summary>A note-off on one track with its release velocity (0..1).</summary>+ public void TrackNoteOffVelocity(int trackId, int pitch, float releaseVelocity)+ { ThrowIfDisposed(); Check(NativeMethods.TrackNoteOffVelocity(_handle, trackId, pitch, releaseVelocity)); }public void TrackNoteOn(int trackId, int pitch, float velocity) { ThrowIfDisposed(); Check(NativeMethods.TrackNoteOn(_handle, trackId, pitch, velocity)); }public void TrackNoteOff(int trackId, int pitch) { ThrowIfDisposed(); Check(NativeMethods.TrackNoteOff(_handle, trackId, pitch)); }public void NoteExpression(int pitch, NoteExpressionDim dim, float value) { ThrowIfDisposed(); Check(NativeMethods.NoteExpression(_handle, pitch, (int)dim, value)); }diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.csindex aaf8f25a..8d87698a 100644--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs@@ -1072,6 +1072,489 @@ public sealed class FactoryPresetCatalog : IFactoryPresetsMos("Warm Pad", "warm-pad", ("attack", 0.71f), ("release", 0.85f), ("velamount", 0.4f));Mos("Warm Pad Filtered", "warm-pad", ("attack", 0.8f), ("release", 0.9f), ("velamount", 0.4f), ("filtertype", 1f / 3f), ("cutoff", 0.55f), ("envcutoff", 1f), ("envamount", 0.7f));+ // ---- Nota Twin (kind 18) — two-part morphing analog poly (specs/055). Tw(name, a, b) writes+ // the Lower part: `a` is side A, side B is A with `b` laid over it, so Morph travels+ // from one sound to a related one. Bare ids are side params ("ldcut" → lo.a.ldcut /+ // lo.b.ldcut); "lo.*" ids are side-less part params.+ // Wave tri/saw/square = 0/.5/1; coarse v = (st + 24)/48; fine .5 + cents/100;+ // cutoff v = log10(Hz/20)/3; env amount .5 + oct/16; attack v = ln(s/0.0005)/ln(20000);+ // decay / release v = ln(s/0.003)/ln(5000); route 0 series … 1 parallel; Filter (bal)+ // 0 multimode … 1 ladder; voice mode Poly/Mono/Legato/Unison = 0/⅓/⅔/1.+ Section("Pads");+ Tw("Warm Two-Filter Pad", P(("lo.vol", 0.6f), ("o2level", 0.8f), ("o2fine", 0.57f), ("o1bal", 0.4f), ("o2bal", 0.7f), ("route", 0.6f),+ ("mmcut", 0.625f), ("mmres", 0.2f), ("ldcut", 0.593f), ("ldres", 0.2f), ("ldenv", 0.6f), ("mmenv", 0.58f),+ ("fenva", 0.6f), ("fenvd", 0.65f), ("fenvs", 0.4f), ("aenva", 0.62f), ("aenvr", 0.7f), ("drift", 0.4f), ("spread", 0.6f)),+ P(("ldcut", 0.78f), ("mmcut", 0.8f), ("mmres", 0.45f), ("o1wave", 0.75f), ("o2wave", 0.25f), ("route", 0.2f), ("aenva", 0.45f)));+ Tw("Glass Pad", P(("o1wave", 0f), ("o1metal", 0.35f), ("o2wave", 0f), ("o2coarse", 0.75f), ("o2level", 0.5f),+ ("o1bal", 0f), ("o2bal", 0f), ("route", 1f), ("mmmode", 0.33f), ("mmcut", 0.7f), ("mmres", 0.35f),+ ("aenva", 0.66f), ("aenvr", 0.76f), ("spread", 0.7f), ("drift", 0.3f)),+ P(("o1metal", 0.8f), ("o2metal", 0.5f), ("mmmode", 0.6f), ("mmres", 0.6f), ("mmcut", 0.8f)));+ Section("Keys");+ Tw("Poly Keys", P(("o2wave", 0.75f), ("o2level", 0.5f), ("ldcut", 0.45f), ("ldenv", 0.72f), ("fenvd", 0.45f),+ ("fenvs", 0.2f), ("fenvvel", 0.6f), ("aenvd", 0.55f), ("aenvs", 0.4f), ("aenvr", 0.45f), ("aenvvel", 0.7f)),+ P(("ldcut", 0.62f), ("ldres", 0.4f), ("fenvd", 0.35f), ("o2coarse", 0.75f), ("aenvs", 0.2f)));+ Tw("Metal Keys", P(("o1wave", 0f), ("o1metal", 0.5f), ("ldcut", 0.7f), ("ldenv", 0.62f), ("fenvd", 0.5f),+ ("fenvs", 0.3f), ("aenvd", 0.6f), ("aenvs", 0.3f), ("aenvr", 0.5f), ("aenvvel", 0.6f)),+ P(("o1metal", 0.9f), ("fm21", 0.35f), ("o2coarse", 0.75f), ("ldcut", 0.85f)));+ Section("Brass");+ Tw("Twin Brass", P(("lo.vol", 0.62f), ("o2level", 1f), ("o1fine", 0.45f), ("o2fine", 0.55f), ("ldcut", 0.4f), ("ldres", 0.15f),+ ("ldenv", 0.7f), ("fenva", 0.4f), ("fenvd", 0.5f), ("fenvs", 0.55f), ("aenva", 0.3f), ("aenvs", 0.85f), ("aenvr", 0.45f)),+ P(("ldcut", 0.55f), ("ldenv", 0.74f), ("fenva", 0.3f), ("drive", 0.35f)));+ Section("Bass");+ Tw("Steiner Bass", P(("lo.voicemode", 1f / 3f), ("lo.glide", 0.3f), ("o1coarse", 0.25f), ("o1wave", 0.75f), ("o1bal", 0f),+ ("route", 1f), ("mmcut", 0.45f), ("mmres", 0.55f), ("mmenv", 0.75f), ("fenvd", 0.45f), ("fenvs", 0.1f), ("drive", 0.4f)),+ P(("mmmode", 0.33f), ("mmres", 0.75f), ("mmenv", 0.85f), ("drive", 0.6f)));+ Tw("Ladder Sub Bass", P(("lo.voicemode", 1f / 3f), ("o1coarse", 0.25f), ("o2coarse", 0f), ("o2level", 0.6f), ("ldcut", 0.35f),+ ("ldres", 0.3f), ("ldenv", 0.62f), ("fenvd", 0.4f), ("fenvs", 0.2f), ("aenvr", 0.3f)),+ P(("ldcut", 0.48f), ("ldres", 0.55f), ("ldslope", 0f), ("brute", 0.3f)));+ Section("Leads");+ Tw("Sync Lead", P(("lo.voicemode", 2f / 3f), ("lo.glide", 0.35f), ("sync", 1f), ("o2coarse", 0.75f), ("o2level", 1f), ("o1level", 0.3f),+ ("ldcut", 0.7f), ("ldenv", 0.6f), ("fenvd", 0.5f), ("vibamt", 0.3f), ("lfo1rate", 0.72f)),+ P(("o2coarse", 0.95f), ("fmfilt", 0.3f), ("ldres", 0.35f)));+ Tw("Brute Lead", P(("lo.voicemode", 1f), ("unidetune", 0.35f), ("brute", 0.6f), ("drive", 0.35f), ("ldcut", 0.6f),+ ("ldres", 0.45f), ("o2level", 0.7f), ("o2wave", 1f), ("vibamt", 0.25f)),+ P(("brute", 0.9f), ("drive", 0.6f), ("ldcut", 0.75f), ("unidetune", 0.55f)));+ Section("Plucks");+ Tw("Twin Pluck", P(("o2wave", 1f), ("o2level", 0.5f), ("ldcut", 0.3f), ("ldres", 0.35f), ("ldenv", 0.8f), ("fenvd", 0.38f),+ ("fenvs", 0f), ("aenvd", 0.45f), ("aenvs", 0f), ("aenvr", 0.45f), ("spread", 0.5f)),+ P(("fenvd", 0.55f), ("aenvd", 0.6f), ("o1wave", 0f), ("o1metal", 0.4f), ("ldres", 0.55f)));+ Section("FX");+ Tw("Noise Sweep", P(("lo.vol", 0.6f), ("o1level", 0f), ("noiselevel", 1f), ("noisebal", 0f), ("route", 1f), ("mmres", 0.85f), ("mmmode", 0.33f),+ ("mmcut", 0.35f), ("mmenv", 0.9f), ("fenva", 0.8f), ("fenvd", 0.85f), ("aenva", 0.5f), ("aenvr", 0.8f)),+ P(("mmmode", 0.9f), ("noisecolor", 0.9f), ("mmcut", 0.55f)));+ Tw("FM Bell", P(("o1wave", 0f), ("fm21", 0.55f), ("o2coarse", 0.896f), ("o2level", 0f), ("ldcut", 0.9f),+ ("aenvd", 0.7f), ("aenvs", 0f), ("aenvr", 0.7f), ("aenvvel", 0.6f)),+ P(("fm21", 0.8f), ("o2coarse", 0.75f), ("o1metal", 0.3f)));++ Section("Pads");+ Tw("Slow Bloom", Cat(P(("o2level", 0.7f), ("o2fine", 0.56f), ("ldcut", 0.42f), ("ldres", 0.25f), ("ldenv", 0.62f), ("fenva", 0.84f), ("fenvd", 0.8f),+ ("fenvs", 0.6f), ("aenva", 0.84f), ("aenvr", 0.74f), ("spread", 0.7f), ("drift", 0.45f), ("revon", 1f), ("revsize", 0.75f), ("revmix", 0.35f)),+ Rt(7, "LFO 2", "ldcut", 0.08f), P(("lfo2rate", 0.25f))),+ P(("ldcut", 0.7f), ("o1metal", 0.4f), ("o1wave", 0.2f), ("mmcut", 0.75f), ("o1bal", 0.5f), ("route", 0.5f), ("revsize", 0.95f)));+ Tw("Dream Morph Pad", Cat(P(("lo.vol", 0.62f), ("o2level", 0.8f), ("o2coarse", 0.646f), ("o2wave", 0f), ("ldcut", 0.5f), ("aenva", 0.77f), ("aenvr", 0.74f),+ ("modfxon", 1f), ("modfxtype", 1f), ("revon", 1f), ("revsize", 0.8f), ("revmix", 0.4f), ("lfo3rate", 0.15f), ("lfo3mode", 1f)),+ Rt(7, "LFO 3", "Morph", 0.9f)),+ P(("o1wave", 1f), ("o1pw", 0.2f), ("ldcut", 0.75f), ("ldres", 0.45f), ("mmmode", 0.5f), ("mmcut", 0.6f), ("o1bal", 0.3f)));+ Tw("Wide Saws", Cat(P(("lo.vol", 0.55f), ("o2level", 0.9f), ("o1fine", 0.42f), ("o2fine", 0.58f), ("ldcut", 0.6f), ("ldenv", 0.55f),+ ("aenva", 0.55f), ("aenvr", 0.65f), ("spread", 1f), ("drift", 0.6f), ("modfxon", 1f), ("modfxmix", 0.45f))),+ P(("o1fine", 0.35f), ("o2fine", 0.65f), ("ldcut", 0.75f), ("modfxtype", 1f), ("dlyon", 1f), ("dlymix", 0.2f)));+ Section("Keys");+ Tw("Twin EP", Cat(P(("o1wave", 0f), ("o1metal", 0.2f), ("o2wave", 0f), ("o2coarse", 0.75f), ("o2level", 0.25f), ("ldcut", 0.6f), ("ldenv", 0.6f),+ ("fenvd", 0.55f), ("fenvs", 0.1f), ("aenvd", 0.72f), ("aenvs", 0.15f), ("aenvr", 0.5f), ("aenvvel", 0.8f), ("modfxon", 1f), ("modfxtype", 0f)),+ Rt(7, "Velocity", "o1metal", 0.3f)),+ P(("o1metal", 0.45f), ("ldcut", 0.72f), ("modfxtype", 2f / 3f)));+ Tw("Clav Funk", Cat(P(("o1wave", 1f), ("o1pw", 0.12f), ("o1bal", 0f), ("route", 1f), ("mmmode", 0.33f), ("mmcut", 0.6f), ("mmres", 0.4f), ("mmenv", 0.7f),+ ("fenvd", 0.38f), ("fenvs", 0f), ("aenvd", 0.5f), ("aenvs", 0f), ("aenvr", 0.3f), ("aenvvel", 0.8f))),+ P(("o1pw", 0.3f), ("mmmode", 0.0f), ("mmres", 0.6f), ("mmenv", 0.8f)));+ Tw("Drawbar Organ", Cat(P(("o1wave", 0f), ("o2wave", 0f), ("o2coarse", 0.75f), ("o2level", 0.6f), ("noiselevel", 0.02f), ("ldcut", 0.85f),+ ("aenva", 0.15f), ("aenvr", 0.3f), ("aenvvel", 0f), ("modfxon", 1f), ("modfxtype", 1f), ("modfxmix", 0.5f))),+ P(("o2coarse", 0.896f), ("o1metal", 0.25f), ("modfxrate", 0.6f), ("drive", 0.3f)));+ Section("Leads");+ Tw("Mono Saw Lead", Cat(P(("lo.voicemode", 2f / 3f), ("lo.glide", 0.4f), ("o2level", 0.8f), ("o2fine", 0.53f), ("ldcut", 0.62f), ("ldres", 0.3f),+ ("ldenv", 0.6f), ("fenvd", 0.55f), ("vibamt", 0.35f), ("lfo1fade", 0.55f), ("dlyon", 1f), ("dlymix", 0.2f))),+ P(("ldcut", 0.78f), ("drive", 0.4f), ("ldres", 0.45f)));+ Tw("Pressure Lead", Cat(P(("lo.voicemode", 1f / 3f), ("lo.glide", 0.3f), ("o1wave", 0.75f), ("o2level", 0.6f), ("ldcut", 0.5f), ("ldres", 0.35f)),+ Rt(7, "Pressure", "brute", 0.6f), Rt(8, "Pressure", "Vibrato", 0.4f)),+ P(("o1wave", 1f), ("ldcut", 0.65f), ("drive", 0.3f)));+ Tw("Filter FM Scream", Cat(P(("lo.vol", 0.6f), ("lo.voicemode", 2f / 3f), ("o2coarse", 0.646f), ("o2level", 0.4f), ("fmfilt", 0.45f), ("o1bal", 0f),+ ("route", 1f), ("mmcut", 0.55f), ("mmres", 0.65f), ("mmenv", 0.65f), ("fenvd", 0.6f), ("drive", 0.35f))),+ P(("fmfilt", 0.75f), ("mmmode", 0.33f), ("mmres", 0.8f)));+ Section("Bass");+ Tw("Pluck Bass", Cat(P(("lo.voicemode", 1f / 3f), ("o1coarse", 0.25f), ("o2coarse", 0.25f), ("o2wave", 1f), ("o2level", 0.6f), ("ldcut", 0.3f),+ ("ldenv", 0.75f), ("fenvd", 0.38f), ("fenvs", 0f), ("aenvd", 0.55f), ("aenvs", 0.2f), ("aenvr", 0.3f))),+ P(("ldcut", 0.4f), ("ldres", 0.4f), ("fenvd", 0.3f)));+ Tw("Acid Ladder", Cat(P(("lo.voicemode", 2f / 3f), ("lo.glide", 0.3f), ("o1coarse", 0.25f), ("o1wave", 0.5f), ("ldcut", 0.3f), ("ldres", 0.75f),+ ("ldenv", 0.8f), ("fenvd", 0.4f), ("fenvs", 0f), ("fenvvel", 0.8f), ("drive", 0.4f))),+ P(("o1wave", 1f), ("ldres", 0.88f), ("ldenv", 0.88f), ("drive", 0.6f)));+ Tw("Sub Wobble", Cat(P(("lo.voicemode", 1f / 3f), ("o1coarse", 0.25f), ("o2coarse", 0f), ("o2level", 0.5f), ("ldcut", 0.4f), ("ldres", 0.4f),+ ("lfo1sync", 1f), ("lfo1div", 9f / 13f), ("vibamt", 0f), ("lfo1mode", 1f)),+ Rt(7, "LFO 1", "ldcut", 0.25f)),+ P(("lfo1div", 11f / 13f), ("ldres", 0.6f), ("drive", 0.35f)));+ Section("Brass");+ Tw("Brass Section", Cat(P(("lo.vol", 0.6f), ("o2level", 1f), ("o1fine", 0.44f), ("o2fine", 0.56f), ("ldcut", 0.42f), ("ldenv", 0.72f), ("fenva", 0.42f),+ ("fenvd", 0.55f), ("fenvs", 0.5f), ("aenva", 0.35f), ("aenvs", 0.8f), ("aenvr", 0.5f), ("spread", 0.8f), ("revon", 1f), ("revmix", 0.2f))),+ P(("ldcut", 0.55f), ("fenva", 0.3f), ("o1wave", 0.6f), ("o2wave", 0.6f)));+ Tw("Soft Horns", Cat(P(("o1wave", 0.35f), ("o2level", 0.6f), ("ldcut", 0.38f), ("ldenv", 0.6f), ("fenva", 0.6f), ("fenvd", 0.6f), ("fenvs", 0.6f),+ ("aenva", 0.55f), ("aenvr", 0.55f), ("vibamt", 0.2f))),+ P(("ldcut", 0.5f), ("o1wave", 0.5f), ("mmcut", 0.7f), ("o1bal", 0.6f)));+ Section("Strings");+ Tw("String Machine", Cat(P(("lo.vol", 0.62f), ("o2level", 0.8f), ("o2coarse", 0.75f), ("ldcut", 0.55f), ("ldenv", 0.5f), ("aenva", 0.7f), ("aenvr", 0.7f),+ ("modfxon", 1f), ("modfxtype", 1f), ("modfxmix", 0.6f), ("revon", 1f), ("revmix", 0.25f))),+ P(("ldcut", 0.68f), ("o1pw", 0.3f), ("o1wave", 0.6f), ("modfxdepth", 0.75f)));+ Tw("Bowed Cello", Cat(P(("lo.voicemode", 2f / 3f), ("lo.glide", 0.25f), ("o1coarse", 0.25f), ("o2coarse", 0.25f), ("o2level", 0.5f), ("o2fine", 0.55f),+ ("ldcut", 0.5f), ("ldres", 0.15f), ("aenva", 0.6f), ("aenvr", 0.5f), ("vibamt", 0.25f), ("lfo1rate", 0.68f), ("lfo1fade", 0.6f),+ ("noiselevel", 0.05f), ("revon", 1f), ("revmix", 0.2f))),+ P(("ldcut", 0.62f), ("o1metal", 0.2f), ("o1wave", 0.45f)));+ Tw("Pizzicato", Cat(P(("o2level", 0.4f), ("ldcut", 0.4f), ("ldenv", 0.7f), ("fenvd", 0.35f), ("fenvs", 0f), ("aenvd", 0.45f), ("aenvs", 0f), ("aenvr", 0.35f),+ ("aenvvel", 0.7f), ("revon", 1f), ("revmix", 0.3f))),+ P(("o1wave", 0.2f), ("ldcut", 0.52f), ("aenvd", 0.55f)));+ Tw("Morphing Strings", Cat(P(("lo.vol", 0.62f), ("o2level", 0.7f), ("o2fine", 0.56f), ("ldcut", 0.45f), ("aenva", 0.72f), ("aenvr", 0.72f),+ ("modfxon", 1f), ("modfxtype", 1f), ("lfo3rate", 0.1f), ("lfo3mode", 1f)),+ Rt(7, "LFO 3", "Morph", 0.8f)),+ P(("ldcut", 0.72f), ("o1wave", 0.75f), ("o2wave", 0.25f), ("ldres", 0.3f)));+ Section("Plucks");+ Tw("Harp Glass", Cat(P(("o1wave", 0f), ("o1metal", 0.3f), ("ldcut", 0.7f), ("aenvd", 0.62f), ("aenvs", 0f), ("aenvr", 0.6f), ("spread", 0.6f),+ ("dlyon", 1f), ("dlymix", 0.2f), ("revon", 1f), ("revmix", 0.3f))),+ P(("o1metal", 0.6f), ("fm21", 0.25f), ("o2coarse", 0.75f)));+ Tw("Kalimba Metal", Cat(P(("o1wave", 0f), ("o1metal", 0.55f), ("fm21", 0.3f), ("o2coarse", 0.896f), ("o2level", 0f), ("ldcut", 0.8f),+ ("aenvd", 0.55f), ("aenvs", 0f), ("aenvr", 0.5f), ("aenvvel", 0.7f))),+ P(("o1metal", 0.8f), ("fm21", 0.5f)));+ Tw("Muted Pluck", Cat(P(("lo.vol", 0.85f), ("o1wave", 0.75f), ("o2level", 0.5f), ("ldcut", 0.45f), ("ldres", 0.2f), ("ldenv", 0.66f), ("fenvd", 0.36f),+ ("fenvs", 0f), ("aenvd", 0.5f), ("aenvs", 0.05f), ("aenvr", 0.35f))),+ P(("ldcut", 0.52f), ("ldres", 0.45f), ("fenvd", 0.42f)));+ Section("Sequences");+ Tw("S&H Bleeps", Cat(P(("o1wave", 1f), ("o1pw", 0.3f), ("o1bal", 0f), ("route", 1f), ("mmmode", 0.2f), ("mmcut", 0.5f), ("mmres", 0.6f),+ ("lfo2shape", 0.8f), ("lfo2sync", 1f), ("lfo2div", 11f / 13f), ("lfo2mode", 1f), ("dlyon", 1f), ("dlymix", 0.3f)),+ Rt(7, "LFO 2", "mmcut", 0.35f)),+ P(("mmmode", 0.5f), ("mmres", 0.75f), ("lfo2div", 9f / 13f)));+ Tw("Pulse Motion", Cat(P(("o2level", 0.6f), ("o2coarse", 0.646f), ("ldcut", 0.5f), ("ldres", 0.35f), ("lfo2shape", 0.6f), ("lfo2sync", 1f),+ ("lfo2div", 9f / 13f), ("lfo2mode", 1f)),+ Rt(7, "LFO 2", "o1level", -0.5f), Rt(8, "LFO 2", "ldcut", 0.15f)),+ P(("lfo2div", 11f / 13f), ("ldres", 0.55f)));+ Tw("Random Steps", Cat(P(("o1wave", 0.75f), ("ldcut", 0.5f), ("ldres", 0.4f), ("aenvd", 0.5f), ("aenvs", 0.2f), ("dlyon", 1f), ("dlymix", 0.3f)),+ Rt(7, "Random", "ldcut", 0.15f), Rt(8, "Random", "o1wave", 0.4f)),+ P(("ldres", 0.6f), ("m8amt", 0.9f)));+ TwSeq("Berlin Bass Seq", P(("lo.voicemode", 1f / 3f), ("o1coarse", 0.25f), ("o1wave", 0.75f), ("ldcut", 0.35f), ("ldres", 0.45f), ("ldenv", 0.7f),+ ("fenvd", 0.36f), ("fenvs", 0f), ("aenvr", 0.3f), ("dlyon", 1f), ("dlymix", 0.2f)),+ P(("ldcut", 0.5f), ("ldres", 0.65f), ("drive", 0.4f)),+ new[] { "C2:110:60%", "C3:80:40%", "C2:100:60%", "G2:80:40%", "C2:110:60%", "C3:80:40%", "D#2:100:50%", "A#2:80:40%",+ "C2:110:60%", "C3:80:40%", "C2:100:60%", "G2:80:40%", "F2:110:60%", "D#2:80:40%", "C2:100:60%", "G1:90:50%" });+ TwSeq("Chord Stabs Seq", P(("seq.rate", 0.4f), ("o2level", 0.7f), ("o2fine", 0.55f), ("ldcut", 0.5f), ("ldenv", 0.7f), ("fenvd", 0.4f), ("fenvs", 0f),+ ("aenvd", 0.5f), ("aenvs", 0f), ("revon", 1f), ("revmix", 0.25f)),+ P(("ldcut", 0.65f), ("o1wave", 1f), ("o1pw", 0.3f)),+ new[] { ".", "C3 D#3 G3:100:40%", ".", "C3 D#3 G3:90:40%", ".", "A#2 D3 F3:100:40%", ".", "G#2 C3 D#3:90:60%" });+ TwSeq("Arp Glass Up", P(("seq.kind", 1f), ("arp.mode", 0f), ("arp.oct", 1f / 3f), ("arp.gate", 0.4f), ("o1wave", 0f), ("o1metal", 0.35f),+ ("ldcut", 0.75f), ("aenvd", 0.55f), ("aenvs", 0.1f), ("dlyon", 1f), ("dlymix", 0.3f)),+ P(("o1metal", 0.7f), ("fm21", 0.3f), ("o2coarse", 0.75f)), new[] { "." });+ TwSeq("Arp Random Bells", P(("seq.kind", 1f), ("arp.mode", 0.6f), ("arp.oct", 2f / 3f), ("arp.gate", 0.3f), ("o1wave", 0f), ("fm21", 0.45f),+ ("o2coarse", 0.896f), ("o2level", 0f), ("ldcut", 0.9f), ("aenvd", 0.6f), ("aenvs", 0f), ("revon", 1f), ("revmix", 0.35f)),+ P(("fm21", 0.7f), ("o1metal", 0.3f)), new[] { "." });+ TwSeq("Arp Chord Pulse", P(("seq.kind", 1f), ("seq.rate", 0.4f), ("arp.mode", 1f), ("arp.gate", 0.5f), ("o2level", 0.7f), ("ldcut", 0.55f),+ ("ldenv", 0.65f), ("fenvd", 0.42f), ("fenvs", 0.1f), ("modfxon", 1f), ("modfxtype", 1f)),+ P(("ldcut", 0.7f), ("ldres", 0.4f)), new[] { "." });+ TwSeq("Morph Sequence", P(("o2level", 0.7f), ("o2coarse", 0.75f), ("ldcut", 0.5f), ("ldenv", 0.6f), ("fenvd", 0.45f), ("aenvd", 0.55f), ("aenvs", 0.2f)),+ P(("o1wave", 1f), ("o1pw", 0.25f), ("ldcut", 0.8f), ("ldres", 0.5f)),+ new[] { "C3:100:70%", "C3:90:70%", "G3:100:70%", "C3:90:70%", "D#3:100:70%", "C3:90:70%", "G3:100:70%", "A#3:90:70%" },+ (21, true, new[] { 0f, 0.15f, 0.3f, 0.45f, 0.6f, 0.75f, 0.9f, 1f })); // lane on "lo.morph" (param 21)+ TwSeq("Tied Melody", P(("lo.voicemode", 2f / 3f), ("lo.glide", 0.35f), ("seq.rate", 0.4f), ("o2level", 0.6f), ("ldcut", 0.55f), ("vibamt", 0.25f),+ ("dlyon", 1f), ("dlymix", 0.25f)),+ P(("ldcut", 0.7f), ("o1wave", 0.7f)),+ new[] { "C4:100:tie", "C4:100:60%", "D#4:90:60%", "G4:100:tie", "G4:100:60%", "F4:90:60%", "D#4:90:tie", "D#4:90:80%" });+ TwSeq("Swing Keys Seq", P(("seq.swing", 0.55f), ("o1wave", 0f), ("o1metal", 0.2f), ("ldcut", 0.6f), ("aenvd", 0.6f), ("aenvs", 0.1f), ("aenvvel", 0.7f),+ ("modfxon", 1f)),+ P(("o1metal", 0.45f), ("ldcut", 0.72f)),+ new[] { "C3 E3:100:50%", "G3:70:40%", "A3:90:50%", "G3:70:40%", "F3 A3:100:50%", "C4:70:40%", "E3:90:50%", "D3:70:40%" });++ Section("FX");+ Tw("Rising Tension", Cat(P(("lo.vol", 0.6f), ("o2level", 0.8f), ("o2fine", 0.6f), ("menva", 0.9f), ("menvs", 1f), ("ldcut", 0.4f), ("aenva", 0.6f),+ ("revon", 1f), ("revmix", 0.4f)),+ Rt(7, "Mod env", "Pitch", 0.25f), Rt(8, "Mod env", "ldcut", 0.4f)),+ P(("o1metal", 0.4f), ("ldres", 0.5f)));+ Tw("Wind Morph", Cat(P(("o1level", 0f), ("noiselevel", 1f), ("noisecolor", 0.8f), ("noisebal", 0f), ("route", 1f), ("mmmode", 0.33f), ("mmcut", 0.55f),+ ("mmres", 0.6f), ("aenva", 0.7f), ("aenvr", 0.75f), ("lfo3rate", 0.2f), ("lfo3mode", 1f), ("revon", 1f), ("revmix", 0.5f)),+ Rt(7, "LFO 3", "mmcut", 0.2f)),+ P(("noisecolor", 0.2f), ("mmmode", 0.66f), ("mmres", 0.8f)));+ Section("Morph");+ Tw("Day to Night", Cat(P(("o1wave", 0.6f), ("o2level", 0.6f), ("o2coarse", 0.75f), ("ldcut", 0.8f), ("aenva", 0.4f), ("aenvr", 0.6f))),+ P(("o1wave", 0.2f), ("o2level", 0.2f), ("ldcut", 0.35f), ("revon", 1f), ("revsize", 0.9f), ("revmix", 0.5f), ("aenva", 0.7f)));+ Tw("Glass to Grit", Cat(P(("lo.vol", 0.5f), ("o1wave", 0f), ("o1metal", 0.3f), ("ldcut", 0.75f), ("aenvr", 0.55f))),+ P(("o1wave", 0.6f), ("o1metal", 0f), ("brute", 0.4f), ("drive", 0.45f), ("ldcut", 0.5f), ("ldres", 0.4f)));+ Tw("Velocity Morph", Cat(P(("lo.morph", 0f), ("o1wave", 0.5f), ("ldcut", 0.4f), ("aenvd", 0.65f), ("aenvs", 0.3f)),+ Rt(7, "Velocity", "Morph", 1f)),+ P(("o1wave", 1f), ("o1pw", 0.25f), ("ldcut", 0.8f), ("ldres", 0.4f)));+ Tw("Key Split Morph", Cat(P(("o2level", 0.5f), ("ldcut", 0.45f)),+ Rt(7, "Key", "Morph", 1f)),+ P(("o1wave", 0f), ("o1metal", 0.5f), ("o2coarse", 0.75f), ("ldcut", 0.85f), ("aenvd", 0.6f), ("aenvs", 0.1f)));+ Tw("Wheel Morph", Cat(P(("o2level", 0.7f), ("ldcut", 0.4f), ("aenva", 0.5f), ("aenvr", 0.6f), ("vibamt", 0f)),+ Rt(7, "Mod wheel", "Morph", 1f)),+ P(("o1wave", 0.9f), ("o2wave", 0.1f), ("ldcut", 0.75f), ("ldres", 0.45f), ("modfxon", 1f)));+ // Two parts (US9): TwParts(name, globals, lower A, lower B, upper A, upper B). mode Layer .5 /+ // Split 1; splitkey = first Upper key / 127; share .25 / .5 / .75 = Lower 4 / 6 / 8 voices.+ Section("Split & Layer");+ TwParts("Bass + Pad Split", P(("mode", 1f), ("splitkey", 48f / 127f), ("share", 0.25f)),+ P(("lo.voicemode", 1f / 3f), ("lo.glide", 0.25f), ("o1coarse", 0.25f), ("o1wave", 0.75f), ("o1bal", 0f), ("route", 1f),+ ("mmcut", 0.45f), ("mmres", 0.5f), ("mmenv", 0.72f), ("fenvd", 0.42f), ("fenvs", 0.15f), ("drive", 0.35f)),+ P(("mmres", 0.7f), ("mmenv", 0.82f)),+ P(("lo.vol", 0.55f), ("o2level", 0.8f), ("o2fine", 0.57f), ("ldcut", 0.6f), ("ldenv", 0.58f), ("fenva", 0.6f), ("fenvd", 0.65f),+ ("aenva", 0.62f), ("aenvr", 0.7f), ("drift", 0.4f), ("spread", 0.6f), ("revon", 1f)),+ P(("ldcut", 0.78f), ("o1wave", 0.75f), ("aenva", 0.45f)));+ TwParts("Sub + Lead Split", P(("mode", 1f), ("splitkey", 53f / 127f), ("share", 0.5f)),+ P(("lo.voicemode", 1f / 3f), ("o1coarse", 0.25f), ("o2coarse", 0f), ("o2level", 0.6f), ("ldcut", 0.35f), ("ldres", 0.3f),+ ("ldenv", 0.62f), ("fenvd", 0.4f), ("fenvs", 0.2f), ("aenvr", 0.3f)),+ P(("ldcut", 0.48f), ("ldres", 0.55f), ("brute", 0.3f)),+ P(("lo.voicemode", 2f / 3f), ("lo.glide", 0.35f), ("o1wave", 0.5f), ("o2wave", 1f), ("o2level", 0.7f), ("o2fine", 0.56f), ("ldcut", 0.55f),+ ("ldres", 0.35f), ("ldenv", 0.66f), ("fenvd", 0.5f), ("fenvs", 0.5f), ("vibamt", 0.25f), ("dlyon", 1f)),+ P(("ldcut", 0.72f), ("ldres", 0.55f), ("drive", 0.45f), ("sync", 1f)));+ TwParts("Keys + Strings Layer", P(("mode", 0.5f), ("share", 0.5f)),+ P(("lo.vol", 0.6f), ("o2wave", 0.75f), ("o2level", 0.5f), ("ldcut", 0.45f), ("ldenv", 0.72f), ("fenvd", 0.45f), ("fenvs", 0.2f),+ ("fenvvel", 0.6f), ("aenvd", 0.55f), ("aenvs", 0.4f), ("aenvr", 0.45f), ("aenvvel", 0.7f)),+ P(("ldcut", 0.62f), ("ldres", 0.4f), ("fenvd", 0.35f)),+ P(("lo.vol", 0.5f), ("o2level", 1f), ("o2fine", 0.58f), ("o1fine", 0.42f), ("ldcut", 0.62f), ("aenva", 0.66f), ("aenvs", 0.9f), ("aenvr", 0.72f),+ ("spread", 0.8f), ("modfxon", 1f), ("revon", 1f)),+ P(("ldcut", 0.75f), ("aenva", 0.55f), ("o1wave", 0.75f)));+ TwParts("Brass + Pad Layer", P(("mode", 0.5f), ("share", 0.5f)),+ P(("lo.vol", 0.6f), ("o2level", 1f), ("o1fine", 0.45f), ("o2fine", 0.55f), ("ldcut", 0.4f), ("ldres", 0.15f), ("ldenv", 0.7f),+ ("fenva", 0.4f), ("fenvd", 0.5f), ("fenvs", 0.55f), ("aenva", 0.3f), ("aenvs", 0.85f), ("aenvr", 0.45f)),+ P(("ldcut", 0.55f), ("ldenv", 0.74f), ("drive", 0.35f)),+ P(("lo.vol", 0.45f), ("o1wave", 0f), ("o1metal", 0.3f), ("o2wave", 0f), ("o2coarse", 0.75f), ("o2level", 0.5f), ("o1bal", 0f), ("o2bal", 0f),+ ("route", 1f), ("mmmode", 0.33f), ("mmcut", 0.7f), ("aenva", 0.7f), ("aenvr", 0.78f), ("spread", 0.7f), ("revon", 1f)),+ P(("o1metal", 0.7f), ("mmcut", 0.8f), ("mmres", 0.5f)));+ TwParts("Glass Bell Layer", P(("mode", 0.5f), ("share", 0.5f)),+ P(("lo.pan", 0.35f), ("lo.vol", 0.55f), ("o1wave", 0f), ("o1metal", 0.5f), ("ldcut", 0.7f), ("ldenv", 0.62f), ("fenvd", 0.5f),+ ("fenvs", 0.3f), ("aenvd", 0.6f), ("aenvs", 0.2f), ("aenvr", 0.6f), ("aenvvel", 0.6f)),+ P(("o1metal", 0.9f), ("fm21", 0.35f), ("o2coarse", 0.75f)),+ P(("lo.pan", 0.65f), ("lo.vol", 0.45f), ("lo.octave", 0.75f), ("o1wave", 0f), ("o2wave", 0f), ("o2coarse", 0.75f), ("o2level", 0.4f),+ ("ldcut", 0.8f), ("aenva", 0.2f), ("aenvd", 0.7f), ("aenvs", 0f), ("aenvr", 0.65f), ("dlyon", 1f)),+ P(("o1metal", 0.6f), ("ldcut", 0.9f)));+ TwParts("Arp Bass + Pad Split", P(("mode", 1f), ("splitkey", 48f / 127f), ("share", 0.25f), ("seq.on", 1f), ("seq.kind", 1f),+ ("seq.target", 0f), ("arp.mode", 0.4f), ("arp.oct", 1f / 3f), ("arp.gate", 0.4f)),+ P(("lo.voicemode", 1f / 3f), ("o1coarse", 0.25f), ("o1wave", 0.5f), ("o2level", 0.6f), ("o2fine", 0.55f), ("ldcut", 0.42f),+ ("ldres", 0.45f), ("ldenv", 0.68f), ("fenvd", 0.35f), ("fenvs", 0.1f), ("aenvd", 0.45f), ("aenvs", 0.5f), ("aenvr", 0.25f)),+ P(("ldcut", 0.55f), ("ldres", 0.6f), ("brute", 0.25f)),+ P(("lo.vol", 0.5f), ("o2level", 0.8f), ("o2fine", 0.58f), ("ldcut", 0.55f), ("aenva", 0.64f), ("aenvr", 0.72f), ("spread", 0.7f),+ ("modfxon", 1f), ("revon", 1f)),+ P(("ldcut", 0.72f), ("o1wave", 0.75f)));++ // ---- more Nota Twin presets: classics, then the morph / sequencer side of it ----------+ Section("Pads");+ Tw("Soft Analog Pad", P(("lo.vol", 0.6f), ("o2level", 0.75f), ("o2fine", 0.55f), ("ldcut", 0.5f), ("ldres", 0.12f), ("ldenv", 0.56f),+ ("fenva", 0.7f), ("fenvd", 0.7f), ("fenvs", 0.6f), ("aenva", 0.7f), ("aenvr", 0.72f), ("drift", 0.35f), ("spread", 0.5f), ("modfxon", 1f)),+ P(("ldcut", 0.62f), ("o1wave", 0.7f), ("o2wave", 0.7f), ("modfxtype", 1f)));+ Tw("Sweep Pad", Cat(P(("lo.vol", 0.58f), ("o2level", 0.8f), ("o2fine", 0.57f), ("ldcut", 0.32f), ("ldres", 0.45f), ("ldenv", 0.78f),+ ("fenva", 0.84f), ("fenvd", 0.84f), ("fenvs", 0.35f), ("aenva", 0.62f), ("aenvr", 0.75f), ("spread", 0.7f), ("revon", 1f), ("revmix", 0.3f))),+ P(("ldres", 0.65f), ("fenva", 0.9f), ("o1wave", 1f), ("o1pw", 0.3f)));+ Tw("Lush Unison Pad", Cat(P(("lo.vol", 0.5f), ("voices", 0.5f), ("lo.voicemode", 1f), ("unidetune", 0.45f), ("ldcut", 0.55f), ("ldenv", 0.55f), ("aenva", 0.66f),+ ("aenvr", 0.7f), ("spread", 1f), ("modfxon", 1f), ("modfxtype", 1f), ("revon", 1f), ("revmix", 0.3f))),+ P(("unidetune", 0.7f), ("ldcut", 0.68f), ("o1wave", 0.75f)));+ Tw("Dark Ambient Pad", Cat(P(("lo.vol", 0.62f), ("o1wave", 0.2f), ("o2wave", 0.3f), ("o2coarse", 0.25f), ("o2level", 0.7f), ("noiselevel", 0.08f),+ ("ldcut", 0.38f), ("ldres", 0.3f), ("aenva", 0.84f), ("aenvr", 0.76f), ("lfo2rate", 0.2f), ("drift", 0.5f),+ ("revon", 1f), ("revsize", 0.9f), ("revmix", 0.45f)),+ Rt(7, "LFO 2", "ldcut", 0.1f)),+ P(("ldcut", 0.5f), ("o1metal", 0.3f), ("noisecolor", 0.2f), ("revdamp", 0.8f)));+ Tw("Warm Choir Pad", Cat(P(("lo.vol", 0.62f), ("o1wave", 0.3f), ("o2level", 0.6f), ("o2fine", 0.56f), ("o1bal", 0.3f), ("o2bal", 0.6f), ("route", 0.6f),+ ("mmmode", 0.5f), ("mmcut", 0.6f), ("mmres", 0.5f), ("ldcut", 0.55f), ("aenva", 0.66f), ("aenvr", 0.7f), ("vibamt", 0.12f),+ ("modfxon", 1f), ("modfxtype", 1f), ("revon", 1f), ("revmix", 0.3f))),+ P(("mmcut", 0.68f), ("mmres", 0.65f), ("o1wave", 0.45f)));+ Section("Keys");+ Tw("Reed Piano", Cat(P(("o1wave", 0.85f), ("o1pw", 0.4f), ("o2wave", 0f), ("o2coarse", 0.75f), ("o2level", 0.3f), ("ldcut", 0.5f), ("ldenv", 0.66f),+ ("fenvd", 0.5f), ("fenvs", 0.15f), ("fenvvel", 0.7f), ("aenvd", 0.66f), ("aenvs", 0.2f), ("aenvr", 0.45f), ("aenvvel", 0.8f), ("modfxon", 1f), ("modfxtype", 2f / 3f)),+ Rt(7, "Velocity", "drive", 0.4f)),+ P(("o1pw", 0.25f), ("ldcut", 0.6f), ("drive", 0.25f)));+ Tw("Poly Stab Keys", Cat(P(("o2level", 0.8f), ("o2fine", 0.55f), ("ldcut", 0.42f), ("ldres", 0.25f), ("ldenv", 0.75f), ("fenvd", 0.42f), ("fenvs", 0f),+ ("aenvd", 0.5f), ("aenvs", 0.1f), ("aenvr", 0.35f), ("revon", 1f), ("revmix", 0.2f))),+ P(("ldres", 0.45f), ("fenvd", 0.36f), ("o1wave", 1f), ("o1pw", 0.35f)));+ Tw("Bell Piano", Cat(P(("o1wave", 0f), ("o1metal", 0.25f), ("o2wave", 0f), ("o2coarse", 0.896f), ("o2level", 0.2f), ("fm21", 0.2f), ("ldcut", 0.7f),+ ("aenvd", 0.72f), ("aenvs", 0.05f), ("aenvr", 0.55f), ("aenvvel", 0.75f), ("revon", 1f), ("revmix", 0.2f))),+ P(("fm21", 0.35f), ("o1metal", 0.4f), ("ldcut", 0.8f)));+ Tw("Synth Clav", Cat(P(("o1wave", 1f), ("o1pw", 0.08f), ("o2wave", 1f), ("o2pw", 0.2f), ("o2coarse", 0.75f), ("o2level", 0.35f), ("ldcut", 0.55f),+ ("ldres", 0.3f), ("ldenv", 0.72f), ("fenvd", 0.34f), ("fenvs", 0f), ("aenvd", 0.42f), ("aenvs", 0f), ("aenvr", 0.25f), ("aenvvel", 0.85f))),+ P(("o1pw", 0.2f), ("ldres", 0.5f), ("fenvd", 0.3f), ("modfxon", 1f), ("modfxtype", 2f / 3f)));+ Tw("Percussive Organ", Cat(P(("o1wave", 0f), ("o2wave", 0f), ("o2coarse", 0.646f), ("o2level", 0.5f), ("ldcut", 0.8f), ("aenvr", 0.25f), ("aenvvel", 0f),+ ("menvd", 0.45f), ("modfxon", 1f), ("modfxtype", 1f)),+ Rt(7, "Mod env", "o2level", 0.4f)),+ P(("o2coarse", 0.75f), ("drive", 0.35f), ("modfxrate", 0.65f)));+ Section("Brass");+ Tw("Synth Brass Swell", Cat(P(("lo.vol", 0.6f), ("o2level", 1f), ("o1fine", 0.46f), ("o2fine", 0.54f), ("ldcut", 0.36f), ("ldenv", 0.74f), ("fenva", 0.62f),+ ("fenvd", 0.65f), ("fenvs", 0.65f), ("aenva", 0.55f), ("aenvs", 0.9f), ("aenvr", 0.5f), ("spread", 0.6f))),+ P(("fenva", 0.72f), ("ldcut", 0.48f), ("ldres", 0.25f)));+ Tw("Bright Brass Stab", Cat(P(("lo.vol", 0.6f), ("o2level", 1f), ("o2fine", 0.55f), ("ldcut", 0.45f), ("ldenv", 0.8f), ("fenva", 0.3f), ("fenvd", 0.45f),+ ("fenvs", 0.3f), ("aenva", 0.25f), ("aenvd", 0.5f), ("aenvs", 0.5f), ("aenvr", 0.4f), ("drive", 0.2f))),+ P(("ldenv", 0.85f), ("drive", 0.4f), ("ldres", 0.3f)));+ Tw("Sync Brass", Cat(P(("lo.vol", 0.55f), ("sync", 1f), ("o2coarse", 0.646f), ("o2level", 1f), ("o1level", 0.4f), ("ldcut", 0.5f), ("ldenv", 0.68f),+ ("fenva", 0.4f), ("fenvd", 0.55f), ("fenvs", 0.5f), ("aenva", 0.35f), ("aenvr", 0.45f), ("menva", 0.45f), ("menvd", 0.6f)),+ Rt(7, "Mod env", "Osc 2 pitch", 0.3f)),+ P(("o2coarse", 0.75f), ("m7amt", 0.75f), ("ldres", 0.3f)));+ Tw("Mellow Brass", Cat(P(("o1wave", 0.4f), ("o2wave", 0.45f), ("o2level", 0.8f), ("o2fine", 0.55f), ("ldcut", 0.34f), ("ldenv", 0.62f), ("fenva", 0.5f),+ ("fenvd", 0.62f), ("fenvs", 0.6f), ("aenva", 0.45f), ("aenvr", 0.5f), ("vibamt", 0.15f), ("revon", 1f), ("revmix", 0.2f))),+ P(("ldcut", 0.44f), ("o1wave", 0.55f), ("o2wave", 0.55f)));+ Section("Bass");+ Tw("Fat Ladder Bass", Cat(P(("lo.voicemode", 1f / 3f), ("o1coarse", 0.25f), ("o2coarse", 0.25f), ("o2level", 0.9f), ("o2fine", 0.54f), ("ldcut", 0.32f),+ ("ldres", 0.35f), ("ldenv", 0.7f), ("fenvd", 0.45f), ("fenvs", 0.2f), ("aenvr", 0.3f), ("drive", 0.3f))),+ P(("ldcut", 0.42f), ("ldres", 0.55f), ("drive", 0.5f)));+ Tw("Saw Bass", Cat(P(("lo.voicemode", 1f / 3f), ("o1coarse", 0.25f), ("o2level", 0.5f), ("o2coarse", 0f), ("o2wave", 0.5f), ("ldcut", 0.42f), ("ldres", 0.2f),+ ("ldenv", 0.65f), ("fenvd", 0.4f), ("fenvs", 0.3f), ("aenvr", 0.25f))),+ P(("ldcut", 0.55f), ("brute", 0.35f)));+ Tw("Square Sub", Cat(P(("lo.voicemode", 1f / 3f), ("o1coarse", 0f), ("o1wave", 1f), ("o2coarse", 0.25f), ("o2wave", 0f), ("o2level", 0.6f), ("ldcut", 0.3f),+ ("ldenv", 0.56f), ("aenvr", 0.3f))),+ P(("o1pw", 0.3f), ("ldcut", 0.38f), ("drive", 0.3f)));+ Tw("Rubber Bass", Cat(P(("lo.voicemode", 2f / 3f), ("lo.glide", 0.25f), ("o1coarse", 0.25f), ("o1wave", 0.75f), ("o1bal", 0f), ("route", 1f), ("mmcut", 0.36f),+ ("mmres", 0.6f), ("mmenv", 0.75f), ("fenvd", 0.42f), ("fenvs", 0.05f), ("fenvvel", 0.6f), ("aenvr", 0.25f))),+ P(("mmres", 0.75f), ("mmenv", 0.82f), ("mmmode", 0.2f)));+ Tw("Reese Bass", Cat(P(("lo.vol", 0.55f), ("lo.voicemode", 1f), ("unidetune", 0.4f), ("o1coarse", 0.25f), ("ldcut", 0.4f), ("ldres", 0.2f),+ ("aenvr", 0.3f), ("modfxon", 1f), ("modfxtype", 1f / 3f), ("modfxmix", 0.3f))),+ P(("unidetune", 0.6f), ("ldcut", 0.5f), ("drive", 0.45f), ("brute", 0.3f)));+ Tw("Glide Mono Bass", Cat(P(("lo.voicemode", 2f / 3f), ("lo.glide", 0.45f), ("lo.glidelegato", 1f), ("o1coarse", 0.25f), ("o1wave", 0.6f), ("o2level", 0.5f),+ ("o2coarse", 0.25f), ("o2fine", 0.56f), ("ldcut", 0.38f), ("ldres", 0.4f), ("ldenv", 0.66f), ("fenvd", 0.5f), ("fenvs", 0.3f))),+ P(("ldcut", 0.5f), ("ldres", 0.6f), ("o1wave", 1f)));+ Section("Leads");+ Tw("Square Lead", Cat(P(("lo.voicemode", 2f / 3f), ("lo.glide", 0.3f), ("o1wave", 1f), ("o1pw", 0.45f), ("ldcut", 0.65f), ("ldenv", 0.56f), ("vibamt", 0.3f),+ ("lfo1fade", 0.55f), ("dlyon", 1f), ("dlymix", 0.2f))),+ P(("o1pw", 0.2f), ("ldcut", 0.75f), ("ldres", 0.3f)));+ Tw("Unison Saw Lead", Cat(P(("lo.vol", 0.55f), ("lo.voicemode", 1f), ("unidetune", 0.35f), ("lo.glide", 0.2f), ("ldcut", 0.66f), ("ldres", 0.2f),+ ("ldenv", 0.6f), ("vibamt", 0.2f), ("dlyon", 1f), ("dlymix", 0.2f), ("revon", 1f), ("revmix", 0.15f))),+ P(("unidetune", 0.55f), ("ldcut", 0.8f), ("drive", 0.3f)));+ Tw("Whistle Lead", Cat(P(("lo.voicemode", 2f / 3f), ("lo.glide", 0.35f), ("o1wave", 0f), ("o1coarse", 0.75f), ("noiselevel", 0.05f), ("ldcut", 0.8f),+ ("aenva", 0.4f), ("aenvr", 0.45f), ("vibamt", 0.35f), ("lfo1rate", 0.7f), ("lfo1fade", 0.6f), ("revon", 1f), ("revmix", 0.3f))),+ P(("o1metal", 0.25f), ("noiselevel", 0.12f), ("vibamt", 0.5f)));+ Tw("Screaming Brute", Cat(P(("lo.vol", 0.5f), ("lo.voicemode", 2f / 3f), ("o2level", 0.8f), ("o2fine", 0.56f), ("brute", 0.75f), ("drive", 0.55f),+ ("ldcut", 0.55f), ("ldres", 0.55f), ("ldenv", 0.62f), ("fenvd", 0.55f))),+ P(("brute", 0.95f), ("ldres", 0.7f), ("ldcut", 0.68f), ("drive", 0.75f)));+ Tw("Portamento Lead", Cat(P(("lo.voicemode", 1f / 3f), ("lo.glide", 0.55f), ("o1wave", 0.6f), ("o2wave", 1f), ("o2level", 0.6f), ("o2coarse", 0.75f),+ ("ldcut", 0.6f), ("ldres", 0.3f), ("vibamt", 0.25f), ("dlyon", 1f), ("dlymix", 0.25f))),+ P(("ldres", 0.45f), ("ldcut", 0.72f), ("o1wave", 0.9f)));+ Section("Plucks");+ Tw("Bright Pluck", Cat(P(("o2level", 0.7f), ("o2fine", 0.55f), ("ldcut", 0.38f), ("ldres", 0.3f), ("ldenv", 0.85f), ("fenvd", 0.36f), ("fenvs", 0f),+ ("aenvd", 0.48f), ("aenvs", 0f), ("aenvr", 0.42f), ("dlyon", 1f), ("dlymix", 0.25f))),+ P(("fenvd", 0.42f), ("ldres", 0.5f), ("o1wave", 1f), ("o1pw", 0.3f)));+ Tw("Marimba", Cat(P(("o1wave", 0f), ("o2wave", 0f), ("o2coarse", 0.896f), ("o2level", 0.15f), ("ldcut", 0.6f), ("ldenv", 0.6f), ("fenvd", 0.34f), ("fenvs", 0f),+ ("aenvd", 0.5f), ("aenvs", 0f), ("aenvr", 0.42f), ("aenvvel", 0.8f), ("revon", 1f), ("revmix", 0.15f))),+ P(("o1metal", 0.3f), ("aenvd", 0.58f), ("ldcut", 0.7f)));+ Tw("Synth Harp", Cat(P(("o1wave", 0.3f), ("o2wave", 0.3f), ("o2coarse", 0.75f), ("o2level", 0.35f), ("ldcut", 0.55f), ("ldenv", 0.66f), ("fenvd", 0.5f),+ ("fenvs", 0f), ("aenvd", 0.66f), ("aenvs", 0f), ("aenvr", 0.62f), ("spread", 0.7f), ("revon", 1f), ("revmix", 0.3f))),+ P(("o1wave", 0f), ("o1metal", 0.3f), ("ldcut", 0.68f)));+ Tw("Short Stab", Cat(P(("lo.vol", 0.62f), ("o2level", 0.8f), ("o2coarse", 0.646f), ("ldcut", 0.5f), ("ldenv", 0.7f), ("fenvd", 0.3f), ("fenvs", 0f),+ ("aenvd", 0.36f), ("aenvs", 0f), ("aenvr", 0.3f), ("revon", 1f), ("revmix", 0.25f))),+ P(("o2coarse", 0.75f), ("ldres", 0.4f), ("drive", 0.3f)));+ Section("Strings");+ Tw("Ensemble Strings", Cat(P(("lo.vol", 0.6f), ("o1wave", 0.55f), ("o2level", 0.8f), ("o2fine", 0.55f), ("ldcut", 0.6f), ("ldenv", 0.52f), ("aenva", 0.62f),+ ("aenvr", 0.68f), ("spread", 0.8f), ("modfxon", 1f), ("modfxtype", 1f), ("modfxmix", 0.55f), ("revon", 1f), ("revmix", 0.25f))),+ P(("ldcut", 0.7f), ("modfxdepth", 0.7f), ("o1pw", 0.3f), ("o1wave", 0.7f)));+ Tw("Slow Violins", Cat(P(("lo.vol", 0.6f), ("o2level", 0.7f), ("o2fine", 0.56f), ("ldcut", 0.5f), ("ldres", 0.1f), ("aenva", 0.75f), ("aenvr", 0.72f),+ ("vibamt", 0.2f), ("lfo1fade", 0.7f), ("spread", 0.7f), ("revon", 1f), ("revsize", 0.7f), ("revmix", 0.3f))),+ P(("ldcut", 0.6f), ("aenva", 0.65f), ("o1metal", 0.15f)));+ Tw("Solo Viola", Cat(P(("lo.voicemode", 2f / 3f), ("lo.glide", 0.2f), ("o2level", 0.4f), ("o2fine", 0.53f), ("ldcut", 0.52f), ("ldres", 0.2f),+ ("aenva", 0.55f), ("aenvr", 0.5f), ("vibamt", 0.3f), ("lfo1rate", 0.66f), ("lfo1fade", 0.6f), ("noiselevel", 0.04f), ("revon", 1f), ("revmix", 0.2f)),+ Rt(7, "Pressure", "ldcut", 0.2f)),+ P(("ldcut", 0.6f), ("o1wave", 0.45f), ("vibamt", 0.4f)));++ Section("Morph");+ Tw("Saw to Bell", Cat(P(("o2level", 0.6f), ("ldcut", 0.55f), ("aenvd", 0.66f), ("aenvs", 0.3f), ("aenvr", 0.55f))),+ P(("o1wave", 0f), ("o1metal", 0.6f), ("fm21", 0.45f), ("o2coarse", 0.896f), ("o2level", 0f), ("ldcut", 0.9f), ("aenvs", 0f)));+ Tw("Bass to Pad", Cat(P(("lo.vol", 0.6f), ("o1coarse", 0.25f), ("o2level", 0.6f), ("ldcut", 0.35f), ("ldenv", 0.7f), ("fenvd", 0.42f), ("fenvs", 0.1f),+ ("aenvr", 0.3f))),+ P(("o1coarse", 0.5f), ("ldcut", 0.6f), ("ldenv", 0.55f), ("fenvd", 0.7f), ("aenva", 0.66f), ("aenvr", 0.72f), ("revon", 1f), ("revmix", 0.35f)));+ Tw("Pressure Bloom", Cat(P(("lo.morph", 0f), ("o2level", 0.6f), ("ldcut", 0.4f), ("aenva", 0.4f), ("aenvr", 0.55f)),+ Rt(7, "Pressure", "Morph", 1f)),+ P(("o1wave", 1f), ("o1pw", 0.25f), ("ldcut", 0.75f), ("ldres", 0.45f), ("modfxon", 1f), ("revon", 1f)));+ Tw("Breathing Morph", Cat(P(("lo.vol", 0.6f), ("o2level", 0.7f), ("o2fine", 0.56f), ("ldcut", 0.45f), ("aenva", 0.6f), ("aenvr", 0.66f),+ ("lfo3shape", 0.2f), ("lfo3rate", 0.2f), ("lfo3sym", 0.85f), ("lfo3curve", 0.7f), ("lfo3mode", 1f)),+ Rt(7, "LFO 3", "Morph", 0.9f)),+ P(("o1wave", 0.9f), ("ldcut", 0.7f), ("ldres", 0.4f), ("mmmode", 0.4f)));+ Tw("Random Morph Keys", Cat(P(("o2level", 0.5f), ("ldcut", 0.5f), ("ldenv", 0.62f), ("fenvd", 0.5f), ("aenvd", 0.6f), ("aenvs", 0.3f)),+ Rt(7, "Random", "Morph", 1f)),+ P(("o1wave", 0f), ("o1metal", 0.5f), ("o2coarse", 0.75f), ("ldcut", 0.7f)));+ Tw("Envelope Morph", Cat(P(("o2level", 0.6f), ("ldcut", 0.5f), ("menva", 0.6f), ("menvd", 0.75f), ("menvs", 0.3f), ("aenva", 0.3f), ("aenvr", 0.6f)),+ Rt(7, "Mod env", "Morph", 1f)),+ P(("o1wave", 1f), ("o1pw", 0.15f), ("o2coarse", 0.646f), ("ldcut", 0.8f), ("ldres", 0.5f)));+ Section("FX");+ Tw("Laser Zap", Cat(P(("o1wave", 0.5f), ("o2level", 0f), ("ldcut", 0.8f), ("menvd", 0.42f), ("aenvd", 0.45f), ("aenvs", 0f), ("aenvr", 0.4f),+ ("dlyon", 1f), ("dlymix", 0.3f)),+ Rt(7, "Mod env", "Pitch", 1f)),+ P(("o1wave", 1f), ("menvd", 0.5f), ("ldres", 0.5f)));+ Tw("Metal Rain", Cat(P(("lo.vol", 0.62f), ("o1wave", 0f), ("o1metal", 0.8f), ("noiselevel", 0.3f), ("noisecolor", 0.8f), ("ldcut", 0.75f),+ ("aenvd", 0.55f), ("aenvs", 0f), ("aenvr", 0.6f), ("dlyon", 1f), ("dlyfb", 0.55f), ("dlymix", 0.35f), ("revon", 1f), ("revmix", 0.35f)),+ Rt(7, "Random", "o1metal", 0.2f)),+ P(("fm21", 0.5f), ("o2coarse", 0.896f), ("o1metal", 1f), ("noisecolor", 0.95f)));+ Tw("Sci-Fi Drone", Cat(P(("lo.vol", 0.55f), ("o2lo", 1f), ("o2level", 0f), ("fm21", 0.5f), ("o1coarse", 0.25f), ("ldcut", 0.45f), ("ldres", 0.55f),+ ("aenva", 0.7f), ("aenvr", 0.8f), ("lfo2rate", 0.15f), ("revon", 1f), ("revsize", 0.9f), ("revmix", 0.45f)),+ Rt(7, "LFO 2", "ldcut", 0.15f)),+ P(("fm21", 0.75f), ("o2coarse", 0.75f), ("ldres", 0.7f), ("brute", 0.3f)));+ Tw("Noise Riser", Cat(P(("lo.vol", 0.6f), ("o1level", 0.3f), ("noiselevel", 1f), ("noisebal", 0f), ("route", 1f), ("mmmode", 0.66f), ("mmcut", 0.3f),+ ("mmres", 0.6f), ("mmenv", 0.85f), ("fenva", 0.92f), ("fenvs", 1f), ("aenva", 0.85f), ("aenvr", 0.7f), ("revon", 1f), ("revmix", 0.4f)),+ Rt(7, "Mod env", "Pitch", 0.3f), P(("menva", 0.92f), ("menvs", 1f))),+ P(("mmmode", 1f), ("mmres", 0.8f), ("noisecolor", 0.85f)));+ Tw("Hollow Wind", Cat(P(("o1level", 0f), ("noiselevel", 1f), ("noisecolor", 0.6f), ("noisebal", 0f), ("route", 1f), ("mmmode", 0.4f), ("mmcut", 0.6f),+ ("mmres", 0.75f), ("mmkey", 1f), ("aenva", 0.66f), ("aenvr", 0.72f), ("lfo2rate", 0.3f), ("revon", 1f), ("revmix", 0.4f)),+ Rt(7, "LFO 2", "mmcut", 0.1f)),+ P(("mmres", 0.88f), ("noisecolor", 0.3f), ("mmmode", 0.55f)));+ Tw("Broken Radio", Cat(P(("lo.vol", 0.6f), ("o1wave", 1f), ("o2level", 0.5f), ("o2coarse", 0.604f), ("fmfilt", 0.35f), ("o1bal", 0f), ("o2bal", 0f),+ ("route", 1f), ("mmmode", 0.5f), ("mmcut", 0.6f), ("mmres", 0.55f), ("lfo2shape", 0.8f), ("lfo2rate", 0.6f), ("lfo2mode", 1f), ("drive", 0.4f)),+ Rt(7, "LFO 2", "mmcut", 0.3f)),+ P(("fmfilt", 0.6f), ("mmres", 0.75f), ("lfo2rate", 0.72f)));+ Section("Keys");+ Tw("Glass Harmonica", Cat(P(("o1wave", 0f), ("o2wave", 0f), ("o2coarse", 0.75f), ("o2fine", 0.53f), ("o2level", 0.5f), ("ldcut", 0.75f), ("aenva", 0.5f),+ ("aenvr", 0.66f), ("vibamt", 0.1f), ("revon", 1f), ("revmix", 0.35f)),+ Rt(7, "Velocity", "o1metal", 0.25f)),+ P(("o1metal", 0.35f), ("o2metal", 0.3f), ("aenva", 0.4f)));+ Section("Bass");+ Tw("FM Growl", Cat(P(("lo.voicemode", 1f / 3f), ("o1coarse", 0.25f), ("fm21", 0.35f), ("o2coarse", 0.25f), ("o2level", 0.3f), ("ldcut", 0.42f),+ ("ldres", 0.4f), ("drive", 0.35f), ("lfo1sync", 1f), ("lfo1div", 9f / 13f), ("lfo1mode", 1f), ("vibamt", 0f)),+ Rt(7, "LFO 1", "fm21", 0.3f)),+ P(("fm21", 0.6f), ("brute", 0.35f), ("ldcut", 0.5f)));++ Section("Sequences");+ TwSeq("Techno Stab Seq", P(("o2level", 0.8f), ("o2coarse", 0.646f), ("ldcut", 0.45f), ("ldres", 0.35f), ("ldenv", 0.72f), ("fenvd", 0.36f), ("fenvs", 0f),+ ("aenvd", 0.42f), ("aenvs", 0f), ("dlyon", 1f), ("dlymix", 0.3f), ("revon", 1f), ("revmix", 0.2f)),+ P(("ldcut", 0.58f), ("ldres", 0.55f)),+ new[] { "C3 D#3 G3:110:30%", ".", ".", "C3 D#3 G3:80:30%", ".", ".", "C3 D#3 G3:100:30%", ".", ".", ".", "A#2 D3 F3:100:30%", ".", ".", "C3 D#3 G3:80:30%", ".", "." });+ TwSeq("Minimal Pluck Seq", P(("o1wave", 0.2f), ("o2level", 0.3f), ("ldcut", 0.5f), ("ldenv", 0.7f), ("fenvd", 0.34f), ("fenvs", 0f), ("aenvd", 0.42f),+ ("aenvs", 0f), ("dlyon", 1f), ("dlyfb", 0.5f), ("dlymix", 0.35f)),+ P(("o1wave", 0f), ("o1metal", 0.4f), ("ldcut", 0.62f)),+ new[] { "C4:100:30%", ".", "G3:80:30%", ".", "D#4:90:30%", ".", "C4:70:30%", "G4:90:30%", ".", "D#4:80:30%", ".", "C4:90:30%", ".", "A#3:80:30%", ".", "G3:70:30%" });+ TwSeq("Acid Line Seq", P(("lo.voicemode", 2f / 3f), ("lo.glide", 0.22f), ("o1coarse", 0.25f), ("o1wave", 0.5f), ("ldcut", 0.32f), ("ldres", 0.78f),+ ("ldenv", 0.8f), ("fenvd", 0.38f), ("fenvs", 0f), ("fenvvel", 0.8f), ("drive", 0.45f), ("dlyon", 1f), ("dlymix", 0.15f)),+ P(("o1wave", 1f), ("ldres", 0.88f), ("drive", 0.6f)),+ new[] { "C2:110:50%", "C3:80:tie", "C3:80:40%", "D#2:100:50%", "C2:110:50%", "G2:80:40%", "A#2:100:tie", "A#2:100:40%",+ "C2:110:50%", "C3:90:40%", "F2:100:50%", "D#2:80:40%", "C2:110:50%", "G1:80:40%", "A#1:100:50%", "C2:120:40%" },+ (21, true, new[] { 0f, 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1f, 0.85f, 0.7f, 0.5f, 0.3f, 0.1f })); // lane on "lo.morph" (param 21)+ TwSeq("Trance Gate Pad", P(("lo.vol", 0.55f), ("o2level", 0.9f), ("o2fine", 0.57f), ("ldcut", 0.6f), ("ldenv", 0.5f), ("aenvd", 0.4f), ("aenvs", 0.6f),+ ("aenvr", 0.3f), ("spread", 0.8f), ("revon", 1f), ("revmix", 0.3f)),+ P(("ldcut", 0.72f), ("ldres", 0.3f), ("o1wave", 0.75f)),+ new[] { "C3 G3 D#4:100:40%", "C3 G3 D#4:70:40%", "C3 G3 D#4:100:40%", ".", "C3 G3 D#4:100:40%", "C3 G3 D#4:70:40%", ".", "C3 G3 D#4:90:40%",+ "A#2 F3 D4:100:40%", "A#2 F3 D4:70:40%", "A#2 F3 D4:100:40%", ".", "G#2 D#3 C4:100:40%", "G#2 D#3 C4:70:40%", ".", "G#2 D#3 C4:90:40%" });+ TwSeq("Swung House Chords", P(("seq.swing", 0.6f), ("o1wave", 0.6f), ("o2level", 0.6f), ("o2coarse", 0.75f), ("ldcut", 0.5f), ("ldenv", 0.66f), ("fenvd", 0.42f),+ ("fenvs", 0.1f), ("aenvd", 0.5f), ("aenvs", 0.2f), ("modfxon", 1f), ("revon", 1f), ("revmix", 0.25f)),+ P(("ldcut", 0.62f), ("o1metal", 0.2f)),+ new[] { ".", ".", "D#3 G3 A#3 D4:100:40%", ".", ".", "D#3 G3 A#3 D4:80:30%", ".", ".", ".", ".", "C3 D#3 G3 A#3:100:40%", ".", ".", "C3 D#3 G3 A#3:80:30%", ".", "." });+ TwSeq("Arp Up Down Saws", P(("seq.kind", 1f), ("arp.mode", 0.4f), ("arp.oct", 1f / 3f), ("arp.gate", 0.45f), ("o2level", 0.7f), ("o2fine", 0.55f),+ ("ldcut", 0.5f), ("ldres", 0.3f), ("ldenv", 0.66f), ("fenvd", 0.4f), ("fenvs", 0.1f), ("dlyon", 1f), ("dlymix", 0.25f)),+ P(("ldcut", 0.65f), ("ldres", 0.5f)), new[] { "." });+ TwSeq("Arp As Played Keys", P(("seq.kind", 1f), ("arp.mode", 0.8f), ("arp.oct", 0f), ("arp.gate", 0.6f), ("seq.rate", 0.2f), ("o1wave", 0f), ("o1metal", 0.25f),+ ("ldcut", 0.65f), ("aenvd", 0.6f), ("aenvs", 0.2f), ("modfxon", 1f), ("revon", 1f), ("revmix", 0.25f)),+ P(("o1metal", 0.5f), ("ldcut", 0.75f)), new[] { "." });+ TwSeq("Arp Octave Bass", P(("seq.kind", 1f), ("arp.mode", 0f), ("arp.oct", 1f / 3f), ("arp.gate", 0.4f), ("lo.voicemode", 1f / 3f), ("o1coarse", 0.25f),+ ("o1wave", 0.75f), ("ldcut", 0.35f), ("ldres", 0.45f), ("ldenv", 0.7f), ("fenvd", 0.36f), ("fenvs", 0f)),+ P(("ldcut", 0.48f), ("ldres", 0.6f), ("drive", 0.4f)), new[] { "." });++ Section("Split & Layer");+ TwParts("Bass + Keys Split", P(("mode", 1f), ("splitkey", 48f / 127f), ("share", 0.25f)),+ P(("lo.voicemode", 1f / 3f), ("o1coarse", 0.25f), ("o2coarse", 0.25f), ("o2level", 0.8f), ("o2fine", 0.54f), ("ldcut", 0.32f), ("ldres", 0.35f),+ ("ldenv", 0.7f), ("fenvd", 0.45f), ("fenvs", 0.2f), ("aenvr", 0.3f)),+ P(("ldcut", 0.42f), ("ldres", 0.55f)),+ P(("lo.vol", 0.55f), ("o1wave", 0f), ("o1metal", 0.2f), ("o2wave", 0f), ("o2coarse", 0.75f), ("o2level", 0.25f), ("ldcut", 0.6f), ("ldenv", 0.6f),+ ("fenvd", 0.55f), ("fenvs", 0.1f), ("aenvd", 0.72f), ("aenvs", 0.15f), ("aenvr", 0.5f), ("modfxon", 1f)),+ P(("o1metal", 0.45f), ("ldcut", 0.72f)));+ TwParts("Organ + Lead Split", P(("mode", 1f), ("splitkey", 60f / 127f), ("share", 0.75f)),+ P(("lo.vol", 0.55f), ("o1wave", 0f), ("o2wave", 0f), ("o2coarse", 0.75f), ("o2level", 0.6f), ("ldcut", 0.85f), ("aenvr", 0.3f), ("aenvvel", 0f),+ ("modfxon", 1f), ("modfxtype", 1f)),+ P(("o2coarse", 0.896f), ("drive", 0.3f)),+ P(("lo.voicemode", 2f / 3f), ("lo.glide", 0.3f), ("o1wave", 1f), ("o1pw", 0.4f), ("ldcut", 0.65f), ("ldenv", 0.56f), ("vibamt", 0.3f), ("dlyon", 1f)),+ P(("o1pw", 0.2f), ("ldcut", 0.75f), ("ldres", 0.35f)));+ TwParts("Pad + Bell Layer", P(("mode", 0.5f), ("share", 0.5f)),+ P(("lo.vol", 0.5f), ("o2level", 0.75f), ("o2fine", 0.55f), ("ldcut", 0.5f), ("aenva", 0.7f), ("aenvr", 0.72f), ("spread", 0.6f), ("modfxon", 1f)),+ P(("ldcut", 0.62f), ("o1wave", 0.7f)),+ P(("lo.vol", 0.42f), ("lo.octave", 0.75f), ("o1wave", 0f), ("fm21", 0.45f), ("o2coarse", 0.896f), ("o2level", 0f), ("ldcut", 0.9f),+ ("aenvd", 0.7f), ("aenvs", 0f), ("aenvr", 0.7f), ("revon", 1f)),+ P(("fm21", 0.7f), ("o1metal", 0.3f)));+ TwParts("Strings + Brass Layer", P(("mode", 0.5f), ("share", 0.5f)),+ P(("lo.vol", 0.5f), ("o1wave", 0.55f), ("o2level", 0.8f), ("o2fine", 0.55f), ("ldcut", 0.6f), ("aenva", 0.62f), ("aenvr", 0.68f), ("spread", 0.8f),+ ("modfxon", 1f), ("modfxtype", 1f)),+ P(("ldcut", 0.7f), ("o1pw", 0.3f)),+ P(("lo.vol", 0.45f), ("o2level", 1f), ("o1fine", 0.46f), ("o2fine", 0.54f), ("ldcut", 0.38f), ("ldenv", 0.72f), ("fenva", 0.45f), ("fenvd", 0.55f),+ ("fenvs", 0.55f), ("aenva", 0.35f), ("aenvr", 0.5f)),+ P(("ldcut", 0.5f), ("drive", 0.3f)));+ TwParts("Wide Detune Layer", P(("mode", 0.5f), ("share", 0.5f)),+ P(("lo.pan", 0.2f), ("lo.vol", 0.5f), ("o1fine", 0.42f), ("o2level", 0.7f), ("o2fine", 0.4f), ("ldcut", 0.6f), ("aenva", 0.5f), ("aenvr", 0.6f)),+ P(("o1wave", 0.8f), ("ldcut", 0.7f)),+ P(("lo.pan", 0.8f), ("lo.vol", 0.5f), ("o1fine", 0.58f), ("o2level", 0.7f), ("o2fine", 0.6f), ("ldcut", 0.6f), ("aenva", 0.5f), ("aenvr", 0.6f)),+ P(("o1wave", 0.8f), ("ldcut", 0.7f)));+ TwParts("Arp Keys + Pad Layer", P(("mode", 0.5f), ("share", 0.5f), ("seq.on", 1f), ("seq.kind", 1f), ("seq.target", 0f), ("arp.mode", 0.4f),+ ("arp.oct", 1f / 3f), ("arp.gate", 0.35f)),+ P(("lo.vol", 0.5f), ("o1wave", 0f), ("o1metal", 0.3f), ("ldcut", 0.7f), ("aenvd", 0.55f), ("aenvs", 0.1f), ("dlyon", 1f), ("dlymix", 0.25f)),+ P(("o1metal", 0.6f), ("fm21", 0.25f), ("o2coarse", 0.75f)),+ P(("lo.vol", 0.45f), ("o2level", 0.8f), ("o2fine", 0.57f), ("ldcut", 0.5f), ("aenva", 0.7f), ("aenvr", 0.74f), ("spread", 0.7f), ("revon", 1f)),+ P(("ldcut", 0.66f), ("o1wave", 0.75f)));+// ---- Nota EQ-8 (kind 0) — raw units. Eq8(…) spells out every band it uses with B(band, type,// Hz, dB, Q, slope, channel); a band it does not name is switched off. Type: 0 Low cut,// 1 Low shelf, 2 Bell, 3 Notch, 4 High shelf, 5 High cut. Slope (cuts): 0 = 12, 1 = 24,@@ -2590,6 +3073,9 @@ public sealed class FactoryPresetCatalog : IFactoryPresetspublic string ResetInPlace(IAudioEngine engine, int trackId, int deviceIndex, bool midiEffect)=> PresetService.ResetInPlace(engine, trackId, deviceIndex, midiEffect);+ public IReadOnlyDictionary<string, float>? InstrumentParams(string id)+ => _byId.TryGetValue(id, out var doc) && doc.NamedParams is { Count: > 0 } named ? named : null;+// Nota Consort preset helpers (see the Consort block above).private static (string, float)[] P(params (string, float)[] ps) => ps;private static (string, float)[] Cat(params (string, float)[][] parts)@@ -2629,6 +3115,75 @@ public sealed class FactoryPresetCatalog : IFactoryPresets_byId["mosaic/" + name].MosaicSource = source;}+ // A Nota Twin matrix route in slot `slot` (7..64; 1–6 hold Init's expression routes) for+ // Tw(): the source by name and the destination as "Morph" / "Pitch" / "Vibrato" / … or a side+ // param id ("ldcut"), depth −1..1 on side A (side B copies it unless Tw's `b` sets "mNamt").+ private static (string Id, float Value)[] Rt(int slot, string source, string destination, float depth)+ {+ int src = System.Array.IndexOf(Nota.Application.Twin.TwinMatrix.Sources, source);+ int dst = destination switch { "Morph" => 1, "Pitch" => 2, "Osc 1 pitch" => 3, "Osc 2 pitch" => 4, "Vibrato" => 5,+ _ => Nota.Application.Twin.TwinMatrix.DestinationOfSide(destination) };+ if (src <= 0 || dst <= 0) throw new System.ArgumentException($"Twin route {source} → {destination}");+ return new[] { ($"lo.m{slot}.src", src / 63f), ($"lo.m{slot}.dst", dst / 255f), ($"m{slot}amt", 0.5f + 0.5f * depth) };+ }++ // Nota Twin's patch-wide params (no part, no side), and the sequencer's ("seq.*", "arp.*").+ private static readonly HashSet<string> TwinGlobals = new() { "mode", "splitkey", "share", "voices", "padx", "pady", "padz", "bendrange" };++ // A Nota Twin preset that plays its own pattern (pattern 1, the sequencer on): `rows` in+ // TwinPatterns' text form; `motion` puts a lane on a param (its index, one value per row).+ private void TwSeq(string name, (string Id, float Value)[] a, (string Id, float Value)[] b, string[] rows,+ (int Param, bool Smooth, float[] Values)? motion = null)+ {+ Tw(name, Cat(P(("seq.on", 1f)), a), b);+ var set = new Nota.Application.Twin.TwinPatterns.Pattern[Nota.Application.Twin.TwinPatterns.Patterns];+ for (int i = 0; i < set.Length; i++) set[i] = new Nota.Application.Twin.TwinPatterns.Pattern();+ set[0].Length = rows.Length;+ for (int k = 0; k < rows.Length; k++)+ set[0].Steps[k] = Nota.Application.Twin.TwinPatterns.ParseStep(rows[k], out var err)+ ?? throw new System.ArgumentException($"Twin preset {name}, row {k + 1}: {err}");+ if (motion is { } m)+ {+ set[0].Lanes[0].Target = m.Param;+ set[0].Lanes[0].Smooth = m.Smooth;+ for (int k = 0; k < m.Values.Length && k < rows.Length; k++) set[0].Lanes[0].Values[k] = (ushort)System.Math.Round(m.Values[k] * 65534);+ }+ _byId["twin/" + name].StateBase64 = System.Convert.ToBase64String(Nota.Application.Twin.TwinPatterns.StateWithPatterns(set));+ }++ // A Nota Twin preset for the Lower part: side A, and side B = A with `b` laid over it.+ // Bare ids are side params; "lo.*" ids are the part's side-less params (specs/055).+ private void Tw(string name, (string Id, float Value)[] a, (string Id, float Value)[] b)+ => Inst("twin", 18, name, TwPart("lo.", a, b).ToArray());++ // One part's params for Tw / TwParts: `a` is side A, side B = A with `b` laid over it; "lo.*"+ // ids are the part's side-less params (renamed to `part`), other dotted ids and the patch-wide+ // ones pass through.+ private static List<(string Id, float Value)> TwPart(string part, (string Id, float Value)[] a, (string Id, float Value)[] b)+ {+ var all = new List<(string Id, float Value)>();+ var side = new Dictionary<string, float>();+ foreach (var (id, v) in a)+ if (id.StartsWith("lo.", System.StringComparison.Ordinal)) all.Add((part + id[3..], v));+ else if (id.Contains('.') || TwinGlobals.Contains(id)) all.Add((id, v));+ else { all.Add((part + "a." + id, v)); side[id] = v; }+ foreach (var (id, v) in b) side[id] = v;+ foreach (var (id, v) in side) all.Add((part + "b." + id, v));+ return all;+ }++ // A two-part Nota Twin preset (US9): `globals` sets the layout ("mode", "splitkey", "share", …),+ // then each part as Tw() writes the Lower — side A, and B = A with its overlay. In the Upper's+ // lists "lo.*" ids name the Upper's own side-less params.+ private void TwParts(string name, (string Id, float Value)[] globals,+ (string Id, float Value)[] lowerA, (string Id, float Value)[] lowerB, (string Id, float Value)[] upperA, (string Id, float Value)[] upperB)+ {+ var all = new List<(string Id, float Value)>(globals);+ all.AddRange(TwPart("lo.", lowerA, lowerB));+ all.AddRange(TwPart("up.", upperA, upperB));+ Inst("twin", 18, name, all.ToArray());+ }+private void Fx(string group, int kind, string name, params (string Name, float Value)[] ps)=> Add(group, name, "builtin-effect", kind, isInstrument: false, isMidi: false, ps);diff --git a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs b/src/managed/Nota.Infrastructure/Persistence/PresetService.csindex 60f1ebc4..6b5b6cda 100644--- a/src/managed/Nota.Infrastructure/Persistence/PresetService.cs+++ b/src/managed/Nota.Infrastructure/Persistence/PresetService.cs@@ -61,6 +61,9 @@ public static class PresetService}// Nota Mosaic: the zone map travels with the sound (its samples stay referenced).if (ik == MosaicModel.Kind && engine.MosaicProgram(trackId) is { Length: > 0 } prog) doc.MosaicProgram = prog;+ // Nota Twin: its sequencer patterns travel with the sound (a params-free state blob).+ if (ik == Nota.Application.Twin.TwinMatrix.Kind && Nota.Application.Twin.TwinPatterns.FromState(engine.GetPluginState(trackId, -1)) is { } pats)+ doc.StateBase64 = Convert.ToBase64String(Nota.Application.Twin.TwinPatterns.StateWithPatterns(pats));return doc;}}@@ -261,6 +264,7 @@ public static class PresetService15 => engine.AddConsortTrack(),16 => engine.AddKeysTrack(),17 => engine.AddMosaicTrack(),+ 18 => engine.AddTwinTrack(),_ => engine.AddInstrumentTrack(),};if (t <= 0) return Loc.T("persistence.preset.failed_to_add_instrument");@@ -272,6 +276,7 @@ public static class PresetService&& doc.NamedParams.TryGetValue(pid, out var v))engine.PluginParamSet(t, -1, i, v);}+ LoadTwinPatterns(doc, engine, t);string mw = LoadMosaicProgram(doc, engine, t);return mw.Length > 0 ? mw : LoadGrainSource(doc, engine, t);}@@ -384,6 +389,19 @@ public static class PresetService/// <summary>Applies a preset to an EXISTING instrument/device in place (no new track//// device is created) — for the in-header preset picker. Built-in instruments reset all/// params to default first so the patch is clean; effects set the preset's named params.</summary>+ // A Nota Twin preset's patterns (a params-free state blob): applied after its params; a preset+ // without patterns leaves the track's own (a sound preset doesn't wipe a sequence). On a Twin+ // already there (undoable) the old patterns come back with the old sound on undo.+ private static void LoadTwinPatterns(PresetDocument doc, IAudioEngine engine, int trackId, bool undoable = false)+ {+ if (string.IsNullOrEmpty(doc.StateBase64)) return;+ byte[] state;+ try { state = Convert.FromBase64String(doc.StateBase64); }+ catch (FormatException) { return; }+ if (undoable) engine.SetInstrumentStateUndoable(trackId, state);+ else engine.SetPluginState(trackId, -1, state);+ }+public static string ApplyInPlace(PresetDocument doc, IAudioEngine engine, int trackId, int deviceIndex){if (trackId <= 0) return Loc.T("common.select_a_track_first");@@ -407,6 +425,7 @@ public static class PresetServicefloat v = named ? doc.NamedParams![id] : engine.InstrumentParamDefault(trackId, i);engine.PluginParamSet(trackId, -1, i, v);}+ if (kind == Nota.Application.Twin.TwinMatrix.Kind) LoadTwinPatterns(doc, engine, trackId, undoable: true);return kind == 10 ? LoadGrainSource(doc, engine, trackId): kind == MosaicModel.Kind ? LoadMosaicProgram(doc, engine, trackId) : "";}diff --git a/src/managed/Nota.Infrastructure/Persistence/PresetStore.cs b/src/managed/Nota.Infrastructure/Persistence/PresetStore.csindex 75c1bdc9..41f208a7 100644--- a/src/managed/Nota.Infrastructure/Persistence/PresetStore.cs+++ b/src/managed/Nota.Infrastructure/Persistence/PresetStore.cs@@ -52,6 +52,16 @@ public sealed class PresetStore : IPresetStorecatch { return null; }}+ public IReadOnlyDictionary<string, float>? InstrumentParams(string path)+ {+ try+ {+ var doc = PresetService.Load(path);+ return doc.Type == "builtin-instrument" && doc.NamedParams is { Count: > 0 } named ? named : null;+ }+ catch { return null; }+ }+public string ApplyFileInPlace(IAudioEngine engine, string path, int trackId, int deviceIndex){try { return PresetService.ApplyInPlace(PresetService.Load(path), engine, trackId, deviceIndex); }diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.csindex a2d942f9..04376ae9 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs@@ -686,6 +686,7 @@ public sealed class ProjectService{ Kind: 15 } => engine.AddConsortTrack(), // Nota Consort{ Kind: 16 } => engine.AddKeysTrack(), // Nota Keys{ Kind: 17 } => engine.AddMosaicTrack(), // Nota Mosaic (its program rides the state blob)+ { Kind: 18 } => engine.AddTwinTrack(), // Nota Twin_ => engine.AddInstrumentTrack(), // Nota Synth};if (t.Instrument?.State is { } synthState)diff --git a/src/managed/Nota.Mcp/Tools/InstrumentTools.cs b/src/managed/Nota.Mcp/Tools/InstrumentTools.csindex 048a68bb..fe4789d1 100644--- a/src/managed/Nota.Mcp/Tools/InstrumentTools.cs+++ b/src/managed/Nota.Mcp/Tools/InstrumentTools.cs@@ -22,7 +22,7 @@ public sealed class InstrumentTools(IAudioEngine engine, IEngineDispatch dispatc(4, "Drum Rack"), (5, "Nota Aurora"), (6, "Nota Volt"),(8, "Nota Pendulum"), (9, "Nota Operator"), (10, "Nota Grain"), (11, "Nota Flux"),(12, "Nota Rhythm"), (13, "Nota Monolith"), (14, "Nota Pentad"), (15, "Nota Consort"),- (16, "Nota Keys"), (17, "Nota Mosaic"),+ (16, "Nota Keys"), (17, "Nota Mosaic"), (18, "Nota Twin"),};public sealed record InstrumentKind(int Kind, string Name);@@ -62,6 +62,7 @@ public sealed class InstrumentTools(IAudioEngine engine, IEngineDispatch dispatc15 => E.AddConsortTrack(),16 => E.AddKeysTrack(),17 => E.AddMosaicTrack(),+ 18 => E.AddTwinTrack(),_ => E.AddVoltSynthTrack(), // the default instrument};// Recorded for "Add track ▸ Recent" (spec 034), like an add from the browser: thediff --git a/src/managed/Nota.Mcp/Tools/TwinTools.cs b/src/managed/Nota.Mcp/Tools/TwinTools.csnew file mode 100644index 00000000..00a1ad31--- /dev/null+++ b/src/managed/Nota.Mcp/Tools/TwinTools.cs@@ -0,0 +1,228 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// MCP tools — Nota Twin (instrument kind 18, specs/055): read the patch with its two morph+// sides and its modulation matrix, and set a matrix route by source / destination name. Every+// other parameter goes through set_instrument_param_by_id with the ids read_twin names.++using System.ComponentModel;+using ModelContextProtocol.Server;+using Nota.Application;+using Nota.Application.Twin;++namespace Nota.Mcp.Tools;++[McpServerToolType]+public sealed class TwinTools(IAudioEngine engine, IEngineDispatch dispatch, IArrangementRefresh refresh)+ : EngineTools(engine, dispatch, refresh)+{+ public sealed record SideRow(string Id, string Name, string A, string B, bool Differs);+ public sealed record RouteRow(int Slot, string Source, string Destination, double DepthAPercent, double DepthBPercent);+ public sealed record PartsInfo(string Layout, string? SplitKey, int LowerVoices, int UpperVoices, string SequencerPlays);+ public sealed record TwinReading(string Summary, double MorphPercent, string VoiceMode, int Voices, int ActiveVoices,+ PartsInfo Parts, SideRow[] Sound, RouteRow[] Routes, string Guide);++ // The controls read_twin reports for each side: the ones that define a patch's character.+ private static readonly string[] MainIds =+ {+ "o1wave", "o1level", "o2wave", "o2level", "o2coarse", "sync", "noiselevel", "mmcut", "mmres", "mmmode",+ "ldcut", "ldres", "ldslope", "route", "brute", "drive", "fenva", "fenvd", "aenva", "aenvd", "aenvs", "aenvr",+ };+ private static readonly string[] VoiceModes = { "Poly", "Mono", "Legato", "Unison" };+ private static readonly string[] Layouts = { "Single", "Layer", "Split" };+ private static readonly string[] SeqTargets = { "Lower", "Upper", "Both" };+ private static readonly string[] NoteNames = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };++ private const string Guide =+ "Ids: '<part>.<side>.<name>' for the sound (part lo = Lower, side a / b; e.g. lo.b.ldcut), '<part>.<name>' for "+ + "side-less part params (lo.morph, lo.voicemode, lo.glide, lo.vol, lo.octave), bare names for the patch (voices, padx, "+ + "bendrange; mode 0 Single / 0.5 Layer / 1 Split, splitkey = first Upper key / 127, share 0 / .25 / .5 / .75 / 1 = Lower "+ + "2 / 4 / 6 / 8 / 10 voices). "+ + "Morph 0 = side A, 1 = side B. Matrix: up to 64 routes per part, each a source, a destination and a depth per side "+ + "(−100..100 %); use set_twin_route.";++ private Dictionary<string, int> Ids(int t)+ {+ int n = E.PluginParamCount(t, -1);+ var m = new Dictionary<string, int>(n);+ for (int i = 0; i < n; i++) m[E.PluginParamId(t, -1, i)] = i;+ return m;+ }++ [McpServerTool(Name = "read_twin"), Description(+ "Read a Nota Twin track (built-in instrument kind 18 — a 12-voice analog poly whose every sound control has a side A and "+ + "a side B, and Morph sweeps between them; two parts, Lower and Upper, layered or split). part 'lo' or 'up' picks the "+ + "part to read. Returns a summary, the parts' layout (Single / Layer / Split, split key, voice share, the part the "+ + "sequencer plays), the morph position, voice mode and voice count, the main "+ + "sound controls with both sides' values (Differs = the morph moves it), every matrix route (slot, source, destination, "+ + "depth on A and on B in %), and an id guide for set_instrument_param_by_id. Null if the track isn't a Twin.")]+ public Task<TwinReading?> ReadTwin(int trackId, string part = "lo") => Read<TwinReading?>(() =>+ {+ if (E.TrackInstrumentKind(trackId) != TwinMatrix.Kind) return null;+ if (part is not ("lo" or "up")) part = "lo";+ var at = Ids(trackId);+ float G(string id) => at.TryGetValue(id, out var i) ? E.PluginParamGet(trackId, -1, i) : 0f;+ string Text(string id) => at.TryGetValue(id, out var i) ? E.PluginParamText(trackId, -1, i) : "";+ var sound = new List<SideRow>();+ foreach (var id in MainIds)+ {+ string a = $"{part}.a.{id}", b = $"{part}.b.{id}";+ string name = E.PluginParamName(trackId, -1, at[a]);+ int dot = name.IndexOf(" · ", StringComparison.Ordinal);+ sound.Add(new SideRow(id, dot >= 0 ? name[(dot + 3)..] : name, Text(a), Text(b), Math.Abs(G(a) - G(b)) > 1e-4f));+ }+ var routes = TwinMatrix.Routes(E, trackId, part).Select(r => new RouteRow(r.Slot, TwinMatrix.Sources[r.Source],+ TwinMatrix.DestinationName(E, trackId, r.Destination), Math.Round(r.DepthA * 100, 1), Math.Round(r.DepthB * 100, 1))).ToArray();+ string mode = VoiceModes[Math.Clamp((int)Math.Round(G(part + ".voicemode") * 3), 0, 3)];+ int voices = 4 + Math.Clamp((int)Math.Round(G("voices") * 8), 0, 8);+ int layout = Math.Clamp((int)Math.Round(G("mode") * 2), 0, 2);+ int lower = layout == 0 ? voices : Math.Clamp(2 + 2 * Math.Clamp((int)Math.Round(G("share") * 4), 0, 4), 2, voices - 2);+ int key = Math.Clamp((int)Math.Round(G("splitkey") * 127), 0, 127);+ var parts = new PartsInfo(Layouts[layout], layout == 2 ? $"{NoteNames[key % 12]}{key / 12 - 1}" : null, lower, voices - lower,+ layout == 0 ? "Lower" : SeqTargets[Math.Clamp((int)Math.Round(G("seq.target") * 2), 0, 2)]);+ int differing = sound.Count(s => s.Differs);+ string partName = part == "lo" ? "Lower" : "Upper";+ string layoutText = layout switch { 1 => $"Layer {lower} + {voices - lower}", 2 => $"Split at {parts.SplitKey} {lower} + {voices - lower}", _ => "Single" };+ string summary = $"Nota Twin · {layoutText} · {partName}: {mode} · morph {G(part + ".morph") * 100:0}% · {differing} of {sound.Count} main controls differ between A and B · {routes.Length} routes";+ return new TwinReading(summary, Math.Round(G(part + ".morph") * 100, 1), mode, voices, E.InstrumentVoiceCount(trackId),+ parts, sound.ToArray(), routes, Guide);+ });++ [McpServerTool(Name = "set_twin_morph_side"), Description(+ "Set sound controls on one morph side of a Nota Twin (kind 18), one undo step. side 'a' or 'b'; values is a list "+ + "'id=value' separated by commas or semicolons, ids without the part / side prefix as read_twin's Sound rows name "+ + "them (e.g. 'ldcut=0.3, o1wave=1, aenva=0.6'), values normalized 0..1. part 'lo' (Lower) or 'up'. Returns what it "+ + "set, or an error line naming the ids it could not find.")]+ public Task<string> SetTwinMorphSide(int trackId, string side, string values, string part = "lo") => Mutate(() =>+ {+ if (E.TrackInstrumentKind(trackId) != TwinMatrix.Kind) return $"error: track {trackId} is not a Nota Twin";+ side = side.Trim().ToLowerInvariant();+ if (side is not ("a" or "b") || part is not ("lo" or "up")) return "error: side a | b, part lo | up";+ var at = Ids(trackId);+ var done = new List<string>();+ var bad = new List<string>();+ foreach (var raw in values.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries))+ {+ var kv = raw.Split('=', 2);+ if (kv.Length != 2 || !float.TryParse(kv[1].Trim(), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var v))+ { bad.Add(raw.Trim()); continue; }+ string id = $"{part}.{side}.{kv[0].Trim()}";+ if (!at.TryGetValue(id, out var i)) { bad.Add(kv[0].Trim()); continue; }+ PlugParam(trackId, -1, i, Math.Clamp(v, 0f, 1f));+ done.Add($"{kv[0].Trim()}={E.PluginParamText(trackId, -1, i)}");+ }+ return bad.Count > 0 ? $"error: unknown or malformed: {string.Join(", ", bad)}" + (done.Count > 0 ? $" (set {string.Join(", ", done)})" : "")+ : $"side {side.ToUpperInvariant()}: {string.Join(", ", done)}";+ });++ [McpServerTool(Name = "copy_twin_side"), Description(+ "Copy or swap the morph sides of a Nota Twin (kind 18) part, one undo step: edit 'a_to_b', 'b_to_a' or 'swap'; part "+ + "'lo' or 'up'. Every sound control and every route depth moves; Morph, the voice settings and the routes' sources and "+ + "destinations stay.")]+ public Task<string> CopyTwinSide(int trackId, string edit, string part = "lo") => Mutate(() =>+ {+ if (E.TrackInstrumentKind(trackId) != TwinMatrix.Kind) return $"error: track {trackId} is not a Nota Twin";+ TwinSides.Edit? op = edit.Trim().ToLowerInvariant() switch+ {+ "a_to_b" => TwinSides.Edit.CopyAToB, "b_to_a" => TwinSides.Edit.CopyBToA, "swap" => TwinSides.Edit.Swap, _ => null,+ };+ if (op is null) return $"error: edit '{edit}' — use a_to_b, b_to_a or swap";+ int n = TwinSides.Apply(E, trackId, op.Value, part);+ return $"{edit}: {n} params";+ });++ public sealed record PatternReading(int Pattern, int Length, string[] Rows, string[] MotionLanes, bool SequencerOn, string Kind);++ [McpServerTool(Name = "get_twin_pattern"), Description(+ "Read one of a Nota Twin's eight sequencer patterns (pattern 1..8): its steps as text rows — notes, then ':velocity' "+ + "and ':gate' ('50%' or 'tie'); '.' is a rest (e.g. 'C3 E3 G3:100:50%') — its motion lanes (target param and how many "+ + "steps set it), and whether the sequencer (or the arpeggiator) is on. Null if the track isn't a Twin.")]+ public Task<PatternReading?> GetTwinPattern(int trackId, int pattern = 1) => Read<PatternReading?>(() =>+ {+ if (E.TrackInstrumentKind(trackId) != TwinMatrix.Kind || pattern is < 1 or > TwinPatterns.Patterns) return null;+ var set = TwinPatterns.FromState(E.GetPluginState(trackId, -1));+ if (set is null) return null;+ var p = set[pattern - 1];+ var at = Ids(trackId);+ var rows = p.Steps.Take(p.Length).Select(TwinPatterns.StepText).ToArray();+ var lanes = p.Lanes.Where(l => l.Target >= 0)+ .Select(l => $"{E.PluginParamId(trackId, -1, l.Target)} ({l.Values.Take(p.Length).Count(v => v != TwinPatterns.MotionUnset)} steps{(l.Smooth ? ", smooth" : "")})").ToArray();+ bool on = E.PluginParamGet(trackId, -1, at["seq.on"]) >= 0.5f;+ string kind = E.PluginParamGet(trackId, -1, at["seq.kind"]) >= 0.5f ? "arpeggiator" : "sequencer";+ return new PatternReading(pattern, p.Length, rows, lanes, on, kind);+ });++ [McpServerTool(Name = "set_twin_pattern"), Description(+ "Replace a Nota Twin sequencer pattern (1..8) with rows in get_twin_pattern's text form, one step per row (rows separated "+ + "by newlines or '|'; 1..64 rows, the count becomes the length). Turns the sequencer on and plays that pattern when "+ + "play = true. One undo step. Returns 'pattern N: L steps' or an error naming the row it couldn't read.")]+ public Task<string> SetTwinPattern(int trackId, string rows, int pattern = 1, bool play = true) => Mutate(() =>+ {+ if (E.TrackInstrumentKind(trackId) != TwinMatrix.Kind) return $"error: track {trackId} is not a Nota Twin";+ if (pattern is < 1 or > TwinPatterns.Patterns) return "error: pattern 1..8";+ var list = rows.Split(new[] { '\n', '|' }, StringSplitOptions.RemoveEmptyEntries).Select(r => r.Trim()).Where(r => r.Length > 0).ToList();+ string err = TwinPatterns.WritePattern(E, trackId, pattern - 1, list);+ if (err.Length > 0) return "error: " + err;+ if (play)+ {+ var at = Ids(trackId);+ PlugParam(trackId, -1, at["seq.on"], 1f);+ PlugParam(trackId, -1, at["seq.pattern"], (pattern - 1) / 7f);+ }+ return $"pattern {pattern}: {list.Count} steps";+ });++ [McpServerTool(Name = "twin_pattern_to_clip"), Description(+ "Write a Nota Twin sequencer pattern (1..8) as an ordinary MIDI clip on its track at a bar (1 = the first bar): notes, "+ + "velocities, gates, ties and swing; motion lanes become automation (existing automation outside the clip stays). Turns "+ + "the sequencer off. One undo step. Returns the clip index, or -1 — also when a clip would play other parts than the "+ + "sequencer does (Layer with Sequencer Target on one part; Split with the target on both parts, or a note on the other "+ + "side of the split key), and for a Twin on a rack chain.")]+ public Task<int> TwinPatternToClip(int trackId, int pattern = 1, int startBar = 1) => Mutate(() =>+ E.TrackInstrumentKind(trackId) != TwinMatrix.Kind ? -1 : TwinPatterns.ToClip(E, trackId, pattern - 1, Math.Max(0, startBar - 1) * 4.0));++ [McpServerTool(Name = "copy_twin_part"), Description(+ "Copy or swap the two parts of a Nota Twin (kind 18), one undo step: edit 'lower_to_upper', 'upper_to_lower' or 'swap'. "+ + "The whole part moves — both morph sides, the matrix, the effects, morph and the voice settings; the layout (mode, split "+ + "key, share) stays. Set mode to Layer / Split with set_instrument_param_by_id to hear the Upper part.")]+ public Task<string> CopyTwinPart(int trackId, string edit) => Mutate(() =>+ {+ if (E.TrackInstrumentKind(trackId) != TwinMatrix.Kind) return $"error: track {trackId} is not a Nota Twin";+ TwinParts.Edit? op = edit.Trim().ToLowerInvariant() switch+ {+ "lower_to_upper" => TwinParts.Edit.CopyLowerToUpper, "upper_to_lower" => TwinParts.Edit.CopyUpperToLower, "swap" => TwinParts.Edit.Swap, _ => null,+ };+ if (op is null) return $"error: edit '{edit}' — use lower_to_upper, upper_to_lower or swap";+ return $"{edit}: {TwinParts.Apply(E, trackId, op.Value)} params";+ });++ [McpServerTool(Name = "set_twin_route"), Description(+ "Set a modulation route on a Nota Twin (kind 18), one undo step. source / destination are names as read_twin and the card "+ + "show them (case-insensitive): sources LFO 1..3, Filter env, Amp env, Mod env, Velocity, Key, Pressure, Slide, Bend, Mod "+ + "wheel, Pitch wheel, Pad X/Y/Z, Random, Macro 1..8; destinations Morph, Pitch, Osc 1 pitch, Osc 2 pitch, Vibrato, or any "+ + "sound control by its name ('Ladder Cutoff', 'Osc1 Wave', 'AmpEnv Attack'). depthA / depthB in % (−100..100; B defaults "+ + "to A). slot 1..64 rewrites that slot; omit it for the first free one. remove = true empties the slot. Returns "+ + "'slot N: source → destination', or an error line ('matrix full', or the name it could not find).")]+ public Task<string> SetTwinRoute(int trackId, string? source = null, string? destination = null, double depthA = 50,+ double? depthB = null, int? slot = null, bool remove = false, string part = "lo") => Mutate(() =>+ {+ if (E.TrackInstrumentKind(trackId) != TwinMatrix.Kind) return $"error: track {trackId} is not a Nota Twin";+ if (part is not ("lo" or "up")) return $"error: part '{part}' — use lo or up";+ if (remove)+ {+ if (slot is not (>= 1 and <= TwinMatrix.Slots)) return "error: remove needs a slot 1..64";+ TwinMatrix.Remove(E, trackId, slot.Value, part);+ return $"slot {slot}: removed";+ }+ int src = Array.FindIndex(TwinMatrix.Sources, s => string.Equals(s, source?.Trim(), StringComparison.OrdinalIgnoreCase));+ if (src <= 0) return $"error: no source '{source}'";+ int dst = -1;+ for (int k = 1; k < TwinMatrix.DestinationCount && dst < 0; k++)+ if (string.Equals(TwinMatrix.DestinationName(E, trackId, k), destination?.Trim(), StringComparison.OrdinalIgnoreCase)) dst = k;+ if (dst <= 0) return $"error: no destination '{destination}'";+ float a = (float)Math.Clamp(depthA / 100, -1, 1), b = (float)Math.Clamp((depthB ?? depthA) / 100, -1, 1);+ int got = TwinMatrix.Add(E, trackId, src, dst, a, b, part, slot ?? 0);+ return got < 0 ? "error: matrix full (64 routes) — remove one first"+ : $"slot {got}: {TwinMatrix.Sources[src]} → {TwinMatrix.DestinationName(E, trackId, dst)} (A {a * 100:0}%, B {b * 100:0}%)";+ });+}diff --git a/src/managed/Nota.Presentation/DeviceInsertService.cs b/src/managed/Nota.Presentation/DeviceInsertService.csindex 46b32350..01adb09d 100644--- a/src/managed/Nota.Presentation/DeviceInsertService.cs+++ b/src/managed/Nota.Presentation/DeviceInsertService.cs@@ -163,6 +163,7 @@ public sealed class DeviceInsertService15 => _engine.AddConsortTrack(),16 => _engine.AddKeysTrack(),17 => _engine.AddMosaicTrack(),+ 18 => _engine.AddTwinTrack(),1 => _engine.AddSamplerInstrumentTrack(),_ => _engine.AddInstrumentTrack(),};diff --git a/src/managed/Nota.Presentation/Racks/RackKeyParams.cs b/src/managed/Nota.Presentation/Racks/RackKeyParams.csindex c0aad43a..a897f60d 100644--- a/src/managed/Nota.Presentation/Racks/RackKeyParams.cs+++ b/src/managed/Nota.Presentation/Racks/RackKeyParams.cs@@ -34,6 +34,7 @@ public static class RackKeyParams[14] = ["Filter Cutoff", "Filter Resonance", "Filter Env-Amount"], // Nota Pentad[15] = ["Filter Cutoff", "Filter Resonance", "Mixer Drive"], // Nota Consort[16] = ["Resonator Bright", "Hammer Hardness", "Tremolo Depth"], // Nota Keys+ [18] = ["Lower A · Ladder Cutoff", "Lower A · Ladder Resonance", "Lower · Morph"], // Nota Twin};// Built-in audio effects by device kind.diff --git a/src/managed/Nota.Remote/RemoteParams.cs b/src/managed/Nota.Remote/RemoteParams.csindex f731b2ae..8c98fbdb 100644--- a/src/managed/Nota.Remote/RemoteParams.cs+++ b/src/managed/Nota.Remote/RemoteParams.cs@@ -32,6 +32,15 @@ public static class RemoteParamspublic const int AutoFilterKind = 7;public const int EffectRackKind = 5;public const int InstrumentRackKind = 3, DrumRackKind = 4, FluxKind = 11, RhythmKind = 12, SamplerKind = 1;+ public const int TwinKind = 18;+ // Nota Twin's phone pages, in order: the morph and the pad, then the Lower part's side-A sound.+ private static readonly string[] TwinRemoteIds =+ {+ "lo.morph", "padx", "pady", "padz", "lo.a.ldcut", "lo.a.ldres", "lo.a.mmcut", "lo.a.mmres",+ "lo.a.o1wave", "lo.a.o2wave", "lo.a.o2level", "lo.a.noiselevel", "lo.a.route", "lo.a.brute", "lo.a.drive", "lo.a.mmmode",+ "lo.a.aenva", "lo.a.aenvd", "lo.a.aenvs", "lo.a.aenvr", "lo.a.fenva", "lo.a.fenvd", "lo.a.ldenv", "lo.a.mmenv",+ "lo.a.vibamt", "lo.a.spread", "lo.a.drift", "lo.glide",+ };private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;@@ -44,7 +53,7 @@ public static class RemoteParams0 => "Nota Synth", 1 => "Sampler", 2 => "Nota Physical", 3 => "Instrument Rack", 4 => "Drum Rack",5 => "Nota Aurora", 6 => "Nota Volt", 7 => "Nota Bass", 8 => "Nota Pendulum", 9 => "Nota Operator",10 => "Nota Grain", 11 => "Nota Flux", 12 => "Nota Rhythm", 13 => "Nota Monolith", 14 => "Nota Pentad",- 15 => "Nota Consort", 16 => "Nota Keys", 17 => "Nota Mosaic", _ => "",+ 15 => "Nota Consort", 16 => "Nota Keys", 17 => "Nota Mosaic", 18 => "Nota Twin", _ => "",};if (name.Length > 0) return name;string id = e.TrackInstrumentPluginId(trackId);@@ -122,6 +131,18 @@ public static class RemoteParams}list.Add(new RemoteMacroDevice(inst + " · Macros", -1, ps));}+ else if (kind == TwinKind)+ {+ // Nota Twin has ~900 params (every sound control on both morph sides of both parts);+ // the phone pages the ones a player reaches for instead (specs/055 research R2a).+ int n = e.PluginParamCount(trackId, -1);+ var at = new Dictionary<string, int>(n);+ for (int i = 0; i < n; i++) at[e.PluginParamId(trackId, -1, i)] = i;+ var picks = new List<int>();+ foreach (var id in TwinRemoteIds)+ if (at.TryGetValue(id, out var pi)) picks.Add(pi);+ AddPaged(list, inst, -1, picks.Count, k => new RemoteParam(RemoteParamKind.PluginParam, trackId, -1, picks[k], e.PluginParamName(trackId, -1, picks[k]), inst));+ }else{int n = e.PluginParamCount(trackId, -1);diff --git a/src/native/nota.engine/CMakeLists.txt b/src/native/nota.engine/CMakeLists.txtindex d53fe320..83abdc91 100644--- a/src/native/nota.engine/CMakeLists.txt+++ b/src/native/nota.engine/CMakeLists.txt@@ -185,6 +185,10 @@ set(NOTA_ENGINE_SOURCESsrc/devices/instruments/RhythmMachine.cppsrc/devices/instruments/MosaicProgram.cpp # program modelsrc/devices/instruments/Mosaic.cpp+ src/devices/instruments/Twin.cpp+ src/devices/instruments/TwinMod.cpp+ src/devices/instruments/TwinSeq.cpp+ src/devices/instruments/TwinVoice.cppsrc/dsp/core/SilenceDetector.cpp # hysteresis silence detectionsrc/dsp/core/Parameter.cpp # param mappings + smoothingsrc/dsp/primitives/SvfFilter.cpp # TPT SVF + LR4diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex 19fd9e09..39b2712b 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -310,6 +310,9 @@ NOTA_API int32_t nota_audition_midi_param(NotaAudition* rig, int32_t index, consNOTA_API int32_t nota_audition_set_sampler_sample(NotaAudition* rig, const char* path_utf8, int32_t root_note);/* Nota Mosaic's program text; returns once its samples are loaded (1) or on failure (0). */NOTA_API int32_t nota_audition_set_mosaic_program(NotaAudition* rig, const char* text_utf8);+/* The instrument's state blob, as nota_engine_set_plugin_state takes it for a built-in+ * instrument (e.g. a Nota Twin preset's patterns), after its params. 1 = applied. */+NOTA_API int32_t nota_audition_instrument_state(NotaAudition* rig, const uint8_t* data, int32_t size);/* Effect source: a file (its first max_seconds), or a demo track mixed from part rigs that* were rendered first (add_source_from). cache_source normalizes the mix to target_peak and* keeps it process-wide under key; use_cached_source takes it back (0 = not cached). */@@ -764,6 +767,9 @@ NOTA_API int32_t nota_engine_add_keys_track(NotaEngine* engine);/* Adds an instrument track with the built-in Nota Mosaic (multisample instrument, kind 17),* empty until a program is set. id (>0). */NOTA_API int32_t nota_engine_add_mosaic_track(NotaEngine* engine);+/* Adds an instrument track with the built-in Nota Twin (two-part morphing analog poly, kind 18).+ * id (>0). */+NOTA_API int32_t nota_engine_add_twin_track(NotaEngine* engine);/* Nota Mosaic's program — UTF-8 text (grammar in Mosaic.h). Set parses it and starts loading* its samples in the background (1 on success, 0 when the track isn't a Mosaic); checkpoint 1* makes it one undo step (the instrument is republished — sounding notes stop), 0 edits the@@ -784,6 +790,10 @@ NOTA_API int64_t nota_file_decode_mono(const char* path_utf8, double max_seconds/* UI editing channel for the track's instrument (e.g. Nota Rhythm step patterns):* id/iarg/farg are instrument-specific (see the instrument's action()). */NOTA_API void nota_track_instrument_action(NotaEngine* engine, int32_t track_id, int32_t id, int32_t iarg, float farg);+/* Loads a state blob into the track's instrument (as nota_plugin_set_state with device -1) and+ * records what it changed in the instrument's edit state (a Nota Twin's patterns) as one undo+ * step — a preset's sequence undoes with its sound. Returns 1 when applied. */+NOTA_API int32_t nota_track_instrument_set_state_undoable(NotaEngine* engine, int32_t track_id, const uint8_t* data, int32_t size);/* Nota Rhythm Phase 2 — per-voice one-shot samples. set returns 1 on success; info fills the* voice's sample id (0 = none); source returns 0 Synth / 1 Sample. */NOTA_API int32_t nota_track_rhythm_set_voice_sample(NotaEngine* engine, int32_t track_id, int32_t voice, const char* path);@@ -874,10 +884,13 @@ NOTA_API NotaResult nota_track_set_armed(NotaEngine* engine, int32_t track_id, i* tracks; captured into the record clip while recording. Lock-free. */NOTA_API NotaResult nota_engine_note_on(NotaEngine* engine, int32_t pitch, float velocity);NOTA_API NotaResult nota_engine_note_off(NotaEngine* engine, int32_t pitch);+/* A live note-off with its release velocity (0..1), as a MIDI note-off message carries it. */+NOTA_API NotaResult nota_engine_note_off_velocity(NotaEngine* engine, int32_t pitch, float release_velocity);/* Live notes addressed to one track, armed or not (Nota Remote: each phone plays its* own track). Recorded only when that track holds the take. Safe from any thread. */NOTA_API NotaResult nota_track_note_on(NotaEngine* engine, int32_t track_id, int32_t pitch, float velocity);NOTA_API NotaResult nota_track_note_off(NotaEngine* engine, int32_t track_id, int32_t pitch);+NOTA_API NotaResult nota_track_note_off_velocity(NotaEngine* engine, int32_t track_id, int32_t pitch, float release_velocity);/* Per-note expression (MPE) for live notes: dim 0 = pitch bend in semitones, 1 = pressure* 0..1, 2 = slide (CC74 timbre) 0..1 with 0.5 neutral, 3 = sustain pedal (CC64) 0..1 (down at >= 0.5) —* instrument-wide only (pitch -1). pitch -1 addresses the whole instrument; its bend is@@ -2024,6 +2037,12 @@ NOTA_API int32_t nota_rack_chain_instrument_scope(const NotaEngine* engine,NOTA_API int32_t nota_rack_chain_instrument_voice_count(const NotaEngine* engine, int32_t track_id, int32_t chain);NOTA_API int32_t nota_rack_chain_instrument_held_notes(const NotaEngine* engine, int32_t track_id, int32_t chain, int32_t* out, int32_t max_n);NOTA_API void nota_rack_chain_instrument_action(NotaEngine* engine, int32_t track_id, int32_t chain, int32_t id, int32_t iarg, float farg);+/* As nota_track_instrument_set_state_undoable, for a chain's instrument. */+NOTA_API int32_t nota_rack_chain_instrument_set_state_undoable(NotaEngine* engine, int32_t track_id, int32_t chain, const uint8_t* data, int32_t size);+/* A chain instrument's params have no undo target: after editing them, pass the state read+ * before (nota_rack_chain_instrument_get_state) and the edit becomes one undo step that swaps+ * the whole state. Joins an open undo group. Returns 1 when recorded. */+NOTA_API int32_t nota_rack_chain_instrument_record_state_undo(NotaEngine* engine, int32_t track_id, int32_t chain, const uint8_t* before, int32_t size);/* Chain instrument GUI + preset (hosted plugins). */NOTA_API void nota_rack_open_chain_instrument_editor(NotaEngine* engine, int32_t track_id, int32_t chain);NOTA_API void nota_rack_open_chain_device_editor(NotaEngine* engine, int32_t track_id, int32_t chain, int32_t dev);@@ -2188,6 +2207,8 @@ NOTA_API int32_t nota_rackdev_chain_instrument_scope(const NotaEngine* engine, iNOTA_API int32_t nota_rackdev_chain_instrument_voice_count(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain);NOTA_API int32_t nota_rackdev_chain_instrument_held_notes(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t* out, int32_t max_n);NOTA_API void nota_rackdev_chain_instrument_action(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, int32_t id, int32_t iarg, float farg);+NOTA_API int32_t nota_rackdev_chain_instrument_record_state_undo(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, const uint8_t* before, int32_t size);+NOTA_API int32_t nota_rackdev_chain_instrument_set_state_undoable(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, const uint8_t* data, int32_t size);NOTA_API void nota_rackdev_open_chain_instrument_editor(NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain);NOTA_API const char* nota_rackdev_chain_instrument_plugin_id(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain);NOTA_API int32_t nota_rackdev_chain_instrument_get_state(const NotaEngine* engine, int32_t track_id, int32_t device_index, int32_t chain, uint8_t* out, int32_t capacity);diff --git a/src/native/nota.engine/src/abi/nota_engine_audition.cpp b/src/native/nota.engine/src/abi/nota_engine_audition.cppindex 3f22d57f..3f100636 100644--- a/src/native/nota.engine/src/abi/nota_engine_audition.cpp+++ b/src/native/nota.engine/src/abi/nota_engine_audition.cpp@@ -46,6 +46,9 @@ int32_t nota_audition_set_sampler_sample(NotaAudition* rig, const char* path, inint32_t nota_audition_set_mosaic_program(NotaAudition* rig, const char* text) {return rig && text && RIG(rig)->setMosaicProgram(std::string(text)) ? 1 : 0;}+int32_t nota_audition_instrument_state(NotaAudition* rig, const uint8_t* data, int32_t size) {+ return rig && data && size > 0 && RIG(rig)->instrumentState(data, size) ? 1 : 0;+}int32_t nota_audition_add_source_from(NotaAudition* rig, const NotaAudition* part, float gain) {return rig && part && RIG(rig)->addSourceFrom(*CRIG(part), gain) ? 1 : 0;}diff --git a/src/native/nota.engine/src/abi/nota_engine_core.cpp b/src/native/nota.engine/src/abi/nota_engine_core.cppindex 043f9adb..188e41ed 100644--- a/src/native/nota.engine/src/abi/nota_engine_core.cpp+++ b/src/native/nota.engine/src/abi/nota_engine_core.cpp@@ -248,6 +248,11 @@ NotaResult nota_engine_note_off(NotaEngine* e, int32_t pitch) {ENG(e)->noteOff(pitch);return NOTA_OK;}+NotaResult nota_engine_note_off_velocity(NotaEngine* e, int32_t pitch, float release_velocity) {+ if (!e || pitch < 0 || pitch > 127) return NOTA_ERR_INVALID_ARG;+ ENG(e)->noteOff(pitch, release_velocity);+ return NOTA_OK;+}NotaResult nota_track_note_on(NotaEngine* e, int32_t track_id, int32_t pitch, float velocity) {if (!e || pitch < 0 || pitch > 127) return NOTA_ERR_INVALID_ARG;ENG(e)->trackNoteOn(track_id, pitch, velocity);@@ -258,6 +263,11 @@ NotaResult nota_track_note_off(NotaEngine* e, int32_t track_id, int32_t pitch) {ENG(e)->trackNoteOff(track_id, pitch);return NOTA_OK;}+NotaResult nota_track_note_off_velocity(NotaEngine* e, int32_t track_id, int32_t pitch, float release_velocity) {+ if (!e || pitch < 0 || pitch > 127) return NOTA_ERR_INVALID_ARG;+ ENG(e)->trackNoteOff(track_id, pitch, release_velocity);+ return NOTA_OK;+}NotaResult nota_engine_note_expression(NotaEngine* e, int32_t pitch, int32_t dim, float value) {if (!e || pitch < -1 || pitch > 127 || dim < 0 || dim > 3 || (dim == 3 && pitch >= 0)) return NOTA_ERR_INVALID_ARG;ENG(e)->noteExpression(pitch, dim, value);diff --git a/src/native/nota.engine/src/abi/nota_engine_rack.cpp b/src/native/nota.engine/src/abi/nota_engine_rack.cppindex 256376f6..84de7941 100644--- a/src/native/nota.engine/src/abi/nota_engine_rack.cpp+++ b/src/native/nota.engine/src/abi/nota_engine_rack.cpp@@ -114,6 +114,16 @@ int32_t nota_rack_chain_instrument_held_notes(const NotaEngine* e, int32_t t, invoid nota_rack_chain_instrument_action(NotaEngine* e, int32_t t, int32_t c, int32_t id, int32_t iarg, float farg) {if (e) ENG(e)->rackChainInstrumentAction(t, -1, c, id, iarg, farg);}+int32_t nota_rack_chain_instrument_record_state_undo(NotaEngine* e, int32_t t, int32_t c, const uint8_t* before, int32_t size) {+ return e && ENG(e)->recordInstrumentState(t, -1, c, before, size) ? 1 : 0;+}+int32_t nota_rackdev_chain_instrument_record_state_undo(NotaEngine* e, int32_t t, int32_t di, int32_t c, const uint8_t* before,+ int32_t size) {+ return e && ENG(e)->recordInstrumentState(t, di, c, before, size) ? 1 : 0;+}+int32_t nota_rack_chain_instrument_set_state_undoable(NotaEngine* e, int32_t t, int32_t c, const uint8_t* data, int32_t size) {+ return e && ENG(e)->instrumentSetStateUndoable(t, -1, c, data, size) ? 1 : 0;+}void nota_rack_open_chain_instrument_editor(NotaEngine* e, int32_t t, int32_t c) {if (e) ENG(e)->rackOpenChainInstrumentEditor(t, -1, c);}@@ -959,6 +969,10 @@ int32_t nota_rackdev_chain_instrument_held_notes(const NotaEngine* e, int32_t t,void nota_rackdev_chain_instrument_action(NotaEngine* e, int32_t t, int32_t di, int32_t c, int32_t id, int32_t iarg, float farg) {if (e) ENG(e)->rackChainInstrumentAction(t, di, c, id, iarg, farg);}+int32_t nota_rackdev_chain_instrument_set_state_undoable(NotaEngine* e, int32_t t, int32_t di, int32_t c, const uint8_t* data,+ int32_t size) {+ return e && ENG(e)->instrumentSetStateUndoable(t, di, c, data, size) ? 1 : 0;+}void nota_rackdev_open_chain_instrument_editor(NotaEngine* e, int32_t t, int32_t di, int32_t c) {if (e) ENG(e)->rackOpenChainInstrumentEditor(t, di, c);}diff --git a/src/native/nota.engine/src/abi/nota_engine_track.cpp b/src/native/nota.engine/src/abi/nota_engine_track.cppindex b2735485..e82b68be 100644--- a/src/native/nota.engine/src/abi/nota_engine_track.cpp+++ b/src/native/nota.engine/src/abi/nota_engine_track.cpp@@ -193,6 +193,9 @@ int32_t nota_engine_add_keys_track(NotaEngine* e) {int32_t nota_engine_add_mosaic_track(NotaEngine* e) {return e ? ENG(e)->addMosaicTrack() : 0;}+int32_t nota_engine_add_twin_track(NotaEngine* e) {+ return e ? ENG(e)->addTwinTrack() : 0;+}int32_t nota_track_mosaic_set_program(NotaEngine* e, int32_t track_id, const char* text, int32_t checkpoint) {return e && text && ENG(e)->mosaicSetProgram(track_id, std::string(text), checkpoint != 0) ? 1 : 0;}@@ -214,6 +217,9 @@ void nota_path_root_set(const char* name, const char* path) {void nota_track_instrument_action(NotaEngine* e, int32_t track_id, int32_t id, int32_t iarg, float farg) {if (e) ENG(e)->instrumentAction(track_id, id, iarg, farg);}+int32_t nota_track_instrument_set_state_undoable(NotaEngine* e, int32_t track_id, const uint8_t* data, int32_t size) {+ return e && ENG(e)->instrumentSetStateUndoable(track_id, -1, -1, data, size) ? 1 : 0;+}int32_t nota_track_rhythm_set_voice_sample(NotaEngine* e, int32_t track_id, int32_t voice, const char* path) {if (!e || !path) return 0;return ENG(e)->setRhythmVoiceSample(track_id, voice, std::string(path)) ? 1 : 0;diff --git a/src/native/nota.engine/src/audio_io/MpeInput.cpp b/src/native/nota.engine/src/audio_io/MpeInput.cppindex 44a561d3..75927a3f 100644--- a/src/native/nota.engine/src/audio_io/MpeInput.cpp+++ b/src/native/nota.engine/src/audio_io/MpeInput.cpp@@ -23,9 +23,11 @@ void MpeInput::message(int32_t status, int32_t channel, int32_t d1, int32_t d2,}break;}- [[fallthrough]];+ out.mpeNoteOff(d1); // a note-on at velocity 0: no release velocity+ c.held[d1 >> 5] &= ~(1u << (d1 & 31));+ break;case 0x80:- out.mpeNoteOff(d1);+ out.mpeNoteOffVelocity(d1, d2 / 127.0f);c.held[d1 >> 5] &= ~(1u << (d1 & 31));break;case 0xE0: {diff --git a/src/native/nota.engine/src/audio_io/MpeInput.h b/src/native/nota.engine/src/audio_io/MpeInput.hindex 26d95144..e32fb3ff 100644--- a/src/native/nota.engine/src/audio_io/MpeInput.h+++ b/src/native/nota.engine/src/audio_io/MpeInput.h@@ -37,6 +37,9 @@ class MpeInput {virtual ~Sink() = default;virtual void mpeNoteOn(int32_t pitch, float velocity) = 0;virtual void mpeNoteOff(int32_t pitch) = 0;+ // A note-off message (0x80) with its release velocity; a sink that doesn't use it+ // gets a plain mpeNoteOff.+ virtual void mpeNoteOffVelocity(int32_t pitch, float /*velocity*/) { mpeNoteOff(pitch); }virtual void mpeExpression(int32_t pitch, int32_t dim, float value) = 0; // pitch −1 = all// An instrument-wide controller (MidiController.h): the wheel, channel pressure and// every CC of an ordinary / master channel, the sustain pedal of any channel.diff --git a/src/native/nota.engine/src/devices/DeviceFactory.cpp b/src/native/nota.engine/src/devices/DeviceFactory.cppindex 7a396770..9c3889f0 100644--- a/src/native/nota.engine/src/devices/DeviceFactory.cpp+++ b/src/native/nota.engine/src/devices/DeviceFactory.cpp@@ -43,6 +43,7 @@#include "devices/midi_fx/MidiVelocity.h"#include "devices/instruments/Monolith.h"#include "devices/instruments/Mosaic.h"+#include "devices/instruments/Twin.h"#include "devices/instruments/OperatorSynth.h"#include "devices/instruments/PendulumSynth.h"#include "devices/instruments/Pentad.h"@@ -114,6 +115,7 @@ std::shared_ptr<Instrument> makeBuiltinInstrument(int32_t kind) {case 15: return std::make_shared<Consort>();case 16: return std::make_shared<Keys>();case 17: return std::make_shared<Mosaic>(); // empty: a program is set later+ case 18: return std::make_shared<Twin>();default: return nullptr; // Racks (3/4) / unknown: no simple swap}}diff --git a/src/native/nota.engine/src/devices/Instrument.h b/src/native/nota.engine/src/devices/Instrument.hindex f0252097..481c8cfa 100644--- a/src/native/nota.engine/src/devices/Instrument.h+++ b/src/native/nota.engine/src/devices/Instrument.h@@ -57,6 +57,9 @@ class Instrument {// eventOffset — see takesTimedEvents).virtual void noteOn(int32_t pitch, float velocity) = 0;virtual void noteOff(int32_t pitch) = 0;+ // A note-off that carries its release velocity (0..1, from a MIDI note-off message); one+ // that doesn't use it gets a plain noteOff. Clip notes and keys without one send noteOff.+ virtual void noteOffVelocity(int32_t pitch, float /*velocity*/) { noteOff(pitch); }virtual void allNotesOff() = 0;// Per-note expression (MPE, see NoteExpression.h): dim is an ExprDim — ExprBend in@@ -112,6 +115,7 @@ class Instrument {// atomics because a rack edit forks the rack on the message thread and carries them over.std::atomic<bool> pedalDown{false};std::atomic<uint64_t> pedalHeld[2] = {0, 0}; // released keys the pedal is holding, one bit per pitch+ std::atomic<uint8_t> pedalRelVel[128] = {}; // their release velocities (×127, 0 = none sent)// Add `frames` of interleaved stereo into `out`. Continues current voices.virtual void render(float* out, int32_t frames) = 0;@@ -259,6 +263,12 @@ class Instrument {// e.g. a drum machine's step patterns / voice selection. id/iarg/farg are// instrument-specific. Default no-op. Message thread.virtual void action(int32_t /*id*/, int32_t /*iarg*/, float /*farg*/) {}+ // The structural state those actions edit (Nota Twin's sequencer patterns), as bytes. When an+ // instrument has one, the engine records every action that changes it as an undo step and+ // undo hands the old bytes back through setEditState — no new instrument is published, so+ // sounding notes go on. Empty = the actions aren't undoable. Message thread.+ virtual std::vector<uint8_t> editState() const { return {}; }+ virtual void setEditState(const uint8_t* /*data*/, int32_t /*size*/) {}// Hosted-plugin parameter automation (M9-B). Values are normalized 0..1 and// identified by a stable string paramID (the index is version-unstable).diff --git a/src/native/nota.engine/src/devices/effects/Delay.cpp b/src/native/nota.engine/src/devices/effects/Delay.cppindex 239a72d1..90acaad1 100644--- a/src/native/nota.engine/src/devices/effects/Delay.cpp+++ b/src/native/nota.engine/src/devices/effects/Delay.cpp@@ -92,6 +92,13 @@ void Delay::process(float* buf, int32_t frames) {const int size = bufL_.capacity();if (size <= 4 || frames <= 0) return;const auto t0 = std::chrono::steady_clock::now();+ // Read first: an exchange on every block would write the flag's cache line each time.+ if (reset_.load(std::memory_order_relaxed) && reset_.exchange(false, std::memory_order_relaxed)) {+ clear_.store(true, std::memory_order_relaxed);+ wowPhase_ = 0.0;+ curL_ = curR_ = oldL_ = oldR_ = 0.0;+ fadePos_ = fadeLen_;+ }if (clear_.exchange(false, std::memory_order_relaxed)) wipe();const bool sync = on(SyncMode) && spb_ > 0.0;@@ -299,6 +306,7 @@ void Delay::setParam(int32_t i, float v) {void Delay::deviceAction(int32_t id, int32_t, float) {if (id == A_ClearLoop) clear_.store(true, std::memory_order_relaxed);+ else if (id == A_Reset) reset_.store(true, std::memory_order_relaxed);wake();}diff --git a/src/native/nota.engine/src/devices/effects/Delay.h b/src/native/nota.engine/src/devices/effects/Delay.hindex eb8b15fb..6451d0b3 100644--- a/src/native/nota.engine/src/devices/effects/Delay.h+++ b/src/native/nota.engine/src/devices/effects/Delay.h@@ -68,7 +68,7 @@ class Delay : public Device {kScope};// deviceAction ids.- enum { A_ClearLoop = 0 };+ enum { A_ClearLoop = 0, A_Reset = 1 }; // A_Reset: the loop, the wow phase and the time glide, as newstatic constexpr float kMaxTimeMs = 2000.0f;static constexpr int kNumDiv = 8;@@ -158,7 +158,7 @@ class Delay : public Device {bool idle_ = false;float loopPk_ = 0.0f; // peak loop-feed push (blocks sleep while the tail rings)- std::atomic<bool> clear_{false};+ std::atomic<bool> clear_{false}, reset_{false};std::atomic<float> mWet_{0}, mOutL_{0}, mOutR_{0}, cpuA_{0}, srA_{44100.0f}, bpmA_{0}, diffA_{0}, msL_{0}, msR_{0};std::atomic<float> p_[kNumParams] = {};};diff --git a/src/native/nota.engine/src/devices/effects/Reverb.cpp b/src/native/nota.engine/src/devices/effects/Reverb.cppindex 5585929d..ee848ab3 100644--- a/src/native/nota.engine/src/devices/effects/Reverb.cpp+++ b/src/native/nota.engine/src/devices/effects/Reverb.cpp@@ -76,6 +76,12 @@ void Reverb::wake() {void Reverb::process(float* buf, int32_t frames) {if (frames <= 0 || preL_.size() < 4) return;const auto t0 = std::chrono::steady_clock::now();+ // Read first: an exchange on every block would write the flag's cache line each time.+ if (reset_.load(std::memory_order_relaxed) && reset_.exchange(false, std::memory_order_relaxed)) {+ kill_.store(true, std::memory_order_relaxed);+ modPhase_ = 0.0;+ span_ = -1.0f;+ }if (kill_.exchange(false, std::memory_order_relaxed)) wipe();const bool freeze = on(Freeze);@@ -324,6 +330,7 @@ bool Reverb::combWrapSelfTest() {void Reverb::deviceAction(int32_t id, int32_t, float) {if (id == A_KillTail) kill_.store(true, std::memory_order_relaxed);+ else if (id == A_Reset) reset_.store(true, std::memory_order_relaxed);wake();}diff --git a/src/native/nota.engine/src/devices/effects/Reverb.h b/src/native/nota.engine/src/devices/effects/Reverb.hindex e0116f7d..ca9bd044 100644--- a/src/native/nota.engine/src/devices/effects/Reverb.h+++ b/src/native/nota.engine/src/devices/effects/Reverb.h@@ -82,7 +82,7 @@ class Reverb : public Device {kScope};// deviceAction ids.- enum { A_KillTail = 0 };+ enum { A_KillTail = 0, A_Reset = 1 }; // A_Reset: the tail, the modulation phase and the size glide, as newReverb();void setSampleRate(double sr, int32_t maxBlock) override;@@ -267,7 +267,7 @@ class Reverb : public Device {bool idle_ = false;float feedPk_ = 0.0f; // peak tank feed (blocks sleep while the tail rings)- std::atomic<bool> kill_{false};+ std::atomic<bool> kill_{false}, reset_{false};std::atomic<float> mWet_{0}, mOutL_{0}, mOutR_{0}, cpuA_{0}, srA_{44100.0f}, rt60A_{0}, preA_{0}, diffA_{0},erOnA_{0};std::atomic<float> p_[kNumParams] = {};diff --git a/src/native/nota.engine/src/devices/instruments/Twin.cpp b/src/native/nota.engine/src/devices/instruments/Twin.cppnew file mode 100644index 00000000..7d2e5bbe--- /dev/null+++ b/src/native/nota.engine/src/devices/instruments/Twin.cpp@@ -0,0 +1,1738 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Twin — the param table, project state and the instrument shell (see Twin.h).+// The three descriptor tables below ARE the persisted layout: their order matches the enums+// in Twin.h and only ever grows at the end.++#include "devices/instruments/Twin.h"+#include "devices/instruments/TwinMod.h"+#include "devices/effects/Chorus.h"+#include "devices/effects/Delay.h"+#include "devices/effects/Flanger.h"+#include "devices/effects/Phaser.h"+#include "devices/effects/Reverb.h"+#include "dsp/core/ScopedNoDenormals.h"++#include <cstdio>+#include <cstring>+#include <unordered_map>++namespace nota {++namespace twin {+namespace {++using D = Domain;++struct Desc {+ const char* id; // id suffix+ const char* name; // display name after the part / side prefix+ float def;+ uint16_t steps;+ Domain domain;+};++constexpr Desc kGlobalDesc[] = {+ {"mode", "Patch Mode", 0.0f, 3, D::Linear},+ {"splitkey", "Patch SplitKey", 60.0f / 127.0f, 128, D::Linear},+ {"share", "Patch VoiceShare", 0.5f, 5, D::Linear},+ {"voices", "Patch Voices", 1.0f, 9, D::Linear},+ {"padx", "Pad X", 0.5f, 0, D::Linear},+ {"pady", "Pad Y", 0.5f, 0, D::Linear},+ {"padz", "Pad Z", 0.0f, 0, D::Linear},+ {"bendrange", "Patch BendRange", 0.0f, 4, D::Linear},+ {"seq.on", "Sequencer On", 0.0f, 2, D::Linear},+ {"seq.kind", "Sequencer Kind", 0.0f, 2, D::Linear},+ {"seq.pattern", "Sequencer Pattern", 0.0f, 8, D::Linear},+ {"seq.rate", "Sequencer Rate", 0.6f, 6, D::Linear},+ {"seq.swing", "Sequencer Swing", 0.0f, 0, D::Linear},+ {"seq.latch", "Sequencer Latch", 0.0f, 2, D::Linear},+ {"seq.transpose", "Sequencer Transpose", 1.0f, 2, D::Linear},+ {"seq.target", "Sequencer Target", 0.0f, 3, D::Linear},+ {"arp.mode", "Arp Mode", 0.0f, 6, D::Linear},+ {"arp.oct", "Arp Octaves", 0.0f, 4, D::Linear},+ {"arp.gate", "Arp Gate", 0.5f, 0, D::Linear},+ {"arp.hold", "Arp Hold", 0.0f, 2, D::Linear},+ {"view", "View", 0.0f, 2, D::Linear}, // 0 = L, 1 = S (InstrumentView); opens as L+};+static_assert(sizeof(kGlobalDesc) / sizeof(kGlobalDesc[0]) == kGlobalN, "global table out of step with Twin.h");++constexpr Desc kPartDesc[] = {+ {"morph", "Morph", 0.0f, 0, D::Linear},+ {"voicemode", "Voice Mode", 0.0f, 4, D::Linear},+ {"glide", "Voice Glide", 0.0f, 0, D::LogTime},+ {"glidelegato", "Voice GlideLegato", 0.0f, 2, D::Linear},+ {"octave", "Voice Octave", 0.5f, 5, D::Linear},+ {"vol", "Out Volume", 0.7f, 0, D::Linear},+ {"pan", "Out Pan", 0.5f, 0, D::Linear},+ {"fxon", "Effects On", 1.0f, 2, D::Linear},+};+static_assert(sizeof(kPartDesc) / sizeof(kPartDesc[0]) == PMacro0, "part table out of step with Twin.h");++constexpr Desc kSideDesc[] = {+ {"o1wave", "Osc1 Wave", 0.5f, 0, D::Linear},+ {"o1pw", "Osc1 PW", 0.5f, 0, D::Linear},+ {"o1metal", "Osc1 Metal", 0.0f, 0, D::Linear},+ {"o1coarse", "Osc1 Coarse", 0.5f, 49, D::Linear},+ {"o1fine", "Osc1 Fine", 0.5f, 0, D::Linear},+ {"o1level", "Osc1 Level", 1.0f, 0, D::Linear},+ {"o1bal", "Osc1 Filter", 1.0f, 0, D::Linear},+ {"o2wave", "Osc2 Wave", 0.5f, 0, D::Linear},+ {"o2pw", "Osc2 PW", 0.5f, 0, D::Linear},+ {"o2metal", "Osc2 Metal", 0.0f, 0, D::Linear},+ {"o2coarse", "Osc2 Coarse", 0.5f, 49, D::Linear},+ {"o2fine", "Osc2 Fine", 0.5f, 0, D::Linear},+ {"o2level", "Osc2 Level", 0.0f, 0, D::Linear},+ {"o2bal", "Osc2 Filter", 1.0f, 0, D::Linear},+ {"sync", "Osc2 Sync", 0.0f, 2, D::Linear},+ {"fm21", "Osc2 FM", 0.0f, 0, D::Linear},+ {"fmfilt", "Osc2 FilterFM", 0.0f, 0, D::Linear},+ {"o2lo", "Osc2 LowFreq", 0.0f, 2, D::Linear},+ {"noiselevel", "Noise Level", 0.0f, 0, D::Linear},+ {"noisecolor", "Noise Colour", 0.5f, 0, D::Linear},+ {"noisebal", "Noise Filter", 1.0f, 0, D::Linear},+ {"mmcut", "Multimode Cutoff", 1.0f, 0, D::Pitch},+ {"mmres", "Multimode Resonance", 0.0f, 0, D::Linear},+ {"mmmode", "Multimode Mode", 0.0f, 0, D::Linear},+ {"mmkey", "Multimode KeyTrack", 0.0f, 0, D::Linear},+ {"mmenv", "Multimode Env", 0.5f, 0, D::Linear},+ {"ldcut", "Ladder Cutoff", 0.7f, 0, D::Pitch},+ {"ldres", "Ladder Resonance", 0.1f, 0, D::Linear},+ {"ldslope", "Ladder Slope", 1.0f, 2, D::Linear},+ {"ldkey", "Ladder KeyTrack", 0.5f, 0, D::Linear},+ {"ldenv", "Ladder Env", 0.6f, 0, D::Linear},+ {"route", "Filters Route", 1.0f, 0, D::Linear},+ {"brute", "Filters Brute", 0.0f, 0, D::Linear},+ {"drive", "Filters Drive", 0.0f, 0, D::Linear},+ {"fenva", "FilterEnv Attack", 0.0f, 0, D::LogTime},+ {"fenvd", "FilterEnv Decay", 0.4f, 0, D::LogTime},+ {"fenvs", "FilterEnv Sustain", 0.5f, 0, D::Linear},+ {"fenvr", "FilterEnv Release", 0.3f, 0, D::LogTime},+ {"fenvvel", "FilterEnv Velocity", 0.3f, 0, D::Linear},+ {"fenvcurve", "FilterEnv Curve", 0.5f, 0, D::Linear},+ {"aenva", "AmpEnv Attack", 0.0f, 0, D::LogTime},+ {"aenvd", "AmpEnv Decay", 0.4f, 0, D::LogTime},+ {"aenvs", "AmpEnv Sustain", 1.0f, 0, D::Linear},+ {"aenvr", "AmpEnv Release", 0.25f, 0, D::LogTime},+ {"aenvvel", "AmpEnv Velocity", 0.5f, 0, D::Linear},+ {"aenvcurve", "AmpEnv Curve", 0.5f, 0, D::Linear},+ {"menvdly", "ModEnv Delay", 0.0f, 0, D::LogTime},+ {"menva", "ModEnv Attack", 0.0f, 0, D::LogTime},+ {"menvd", "ModEnv Decay", 0.4f, 0, D::LogTime},+ {"menvs", "ModEnv Sustain", 0.0f, 0, D::Linear},+ {"menvr", "ModEnv Release", 0.3f, 0, D::LogTime},+ {"menvvel", "ModEnv Velocity", 0.0f, 0, D::Linear},+ {"menvloop", "ModEnv Loop", 0.0f, 2, D::Linear},+ {"lfo1shape", "LFO1 Shape", 0.0f, 6, D::Linear},+ {"lfo1rate", "LFO1 Rate", 0.45f, 0, D::LogTime},+ {"lfo1sync", "LFO1 Sync", 0.0f, 2, D::Linear},+ {"lfo1div", "LFO1 Division", 0.5f, 14, D::Linear},+ {"lfo1mode", "LFO1 Mode", 0.0f, 2, D::Linear},+ {"lfo1retrig", "LFO1 Retrigger", 0.0f, 2, D::Linear},+ {"lfo1fade", "LFO1 Fade", 0.0f, 0, D::LogTime},+ {"lfo1amt", "LFO1 Amount", 1.0f, 0, D::Linear},+ {"lfo2shape", "LFO2 Shape", 0.0f, 6, D::Linear},+ {"lfo2rate", "LFO2 Rate", 0.35f, 0, D::LogTime},+ {"lfo2sync", "LFO2 Sync", 0.0f, 2, D::Linear},+ {"lfo2div", "LFO2 Division", 0.5f, 14, D::Linear},+ {"lfo2mode", "LFO2 Mode", 0.0f, 2, D::Linear},+ {"lfo2retrig", "LFO2 Retrigger", 0.0f, 2, D::Linear},+ {"lfo2fade", "LFO2 Fade", 0.0f, 0, D::LogTime},+ {"lfo2amt", "LFO2 Amount", 1.0f, 0, D::Linear},+ {"lfo3shape", "LFO3 Shape", 0.0f, 6, D::Linear},+ {"lfo3rate", "LFO3 Rate", 0.25f, 0, D::LogTime},+ {"lfo3sync", "LFO3 Sync", 0.0f, 2, D::Linear},+ {"lfo3div", "LFO3 Division", 0.5f, 14, D::Linear},+ {"lfo3mode", "LFO3 Mode", 1.0f, 2, D::Linear},+ {"lfo3retrig", "LFO3 Retrigger", 0.0f, 2, D::Linear},+ {"lfo3fade", "LFO3 Fade", 0.0f, 0, D::LogTime},+ {"lfo3amt", "LFO3 Amount", 1.0f, 0, D::Linear},+ {"lfo3sym", "LFO3 Symmetry", 0.5f, 0, D::Linear},+ {"lfo3curve", "LFO3 Curve", 0.5f, 0, D::Linear},+ {"vibamt", "Perform Vibrato", 0.15f, 0, D::Linear},+ {"drift", "Voice Drift", 0.2f, 0, D::Linear},+ {"unidetune", "Voice UniDetune", 0.3f, 0, D::Linear},+ {"spread", "Voice Spread", 0.3f, 0, D::Linear},+ {"spreadmode", "Voice SpreadMode", 0.0f, 3, D::Linear},+ {"modfxtype", "ModFX Type", 0.0f, 4, D::Linear},+ {"modfxrate", "ModFX Rate", 0.3f, 0, D::LogTime},+ {"modfxdepth", "ModFX Depth", 0.5f, 0, D::Linear},+ {"modfxmix", "ModFX Mix", 0.3f, 0, D::Linear},+ {"dlytime", "Delay Time", 0.2f, 0, D::Linear}, // the Delay device: 2 s × v+ {"dlysync", "Delay Sync", 1.0f, 2, D::Linear},+ {"dlydiv", "Delay Division", 5.0f / 7.0f, 8, D::Linear}, // the Delay device's 1/16 … 1/2+ {"dlyfb", "Delay Feedback", 0.35f, 0, D::Linear},+ {"dlypingpong", "Delay PingPong", 1.0f, 2, D::Linear},+ {"dlymix", "Delay Mix", 0.25f, 0, D::Linear},+ {"revsize", "Reverb Size", 0.5f, 0, D::Linear},+ {"revdamp", "Reverb Damping", 0.5f, 0, D::Linear},+ {"revmix", "Reverb Mix", 0.2f, 0, D::Linear},+ {"modfxon", "ModFX On", 0.0f, 2, D::Linear},+ {"dlyon", "Delay On", 0.0f, 2, D::Linear},+ {"revon", "Reverb On", 0.0f, 2, D::Linear},+};+static_assert(sizeof(kSideDesc) / sizeof(kSideDesc[0]) == MatAmt0, "side table out of step with Twin.h");++ParamInfo make(const std::string& idPrefix, const std::string& namePrefix, const Desc& d) {+ return {idPrefix + d.id, namePrefix + d.name, d.def, d.steps, d.domain};+}++std::vector<ParamInfo> buildTable() {+ std::vector<ParamInfo> t;+ t.reserve(kNumParams);+ for (const Desc& d : kGlobalDesc) t.push_back(make("", "", d));+ static const char* const partId[kParts] = {"lo.", "up."};+ static const char* const partName[kParts] = {"Lower", "Upper"};+ static const char* const sideId[kSides] = {"a.", "b."};+ static const char* const sideName[kSides] = {" A", " B"};+ char buf[64];+ for (int p = 0; p < kParts; ++p) {+ const std::string pid = partId[p], pname = std::string(partName[p]) + " · ";+ for (const Desc& d : kPartDesc) t.push_back(make(pid, pname, d));+ for (int m = 0; m < kMacros; ++m) {+ std::snprintf(buf, sizeof buf, "macro%d", m + 1);+ std::string id = pid + buf;+ std::snprintf(buf, sizeof buf, "Macros Macro%d", m + 1);+ t.push_back({id, pname + buf, 0.0f, 0, Domain::Linear});+ }+ for (int r = 0; r < kRoutes; ++r) {+ std::snprintf(buf, sizeof buf, "m%d.src", r + 1);+ std::string sid = pid + buf;+ std::snprintf(buf, sizeof buf, "m%d.dst", r + 1);+ std::string did = pid + buf;+ std::snprintf(buf, sizeof buf, "Routing Source%d", r + 1);+ t.push_back({sid, pname + buf, 0.0f, kSrcScale + 1, Domain::Linear});+ std::snprintf(buf, sizeof buf, "Routing Destination%d", r + 1);+ t.push_back({did, pname + buf, 0.0f, kDstScale + 1, Domain::Linear});+ }+ for (int s = 0; s < kSides; ++s) {+ const std::string sid = pid + sideId[s], sname = std::string(partName[p]) + sideName[s] + " · ";+ for (const Desc& d : kSideDesc) t.push_back(make(sid, sname, d));+ for (int r = 0; r < kRoutes; ++r) {+ std::snprintf(buf, sizeof buf, "m%damt", r + 1);+ std::string id = sid + buf;+ std::snprintf(buf, sizeof buf, "Routing Depth%d", r + 1);+ t.push_back({id, sname + buf, 0.5f, 0, Domain::Linear});+ }+ }+ }+ // Init's routes (FR-033), removable like any other: pressure opens both cutoffs, slide and+ // pad X sweep the multimode, pad Y leans the morph, pad Z deepens the vibrato.+ struct Def {+ int src;+ int dst;+ float depth; // bipolar −1..1+ };+ const Def defs[] = {{SrcPressure, dstIndexOfSide(LdCut), 0.15f}, {SrcPressure, dstIndexOfSide(MmCut), 0.15f},+ {SrcSlide, dstIndexOfSide(MmCut), 0.2f}, {SrcPadX, dstIndexOfSide(MmCut), 0.2f}, {SrcPadY, kDstMorph, 0.5f},+ {SrcPadZ, kDstVibrato, 0.15f}};+ for (int p = 0; p < kParts; ++p)+ for (int r = 0; r < static_cast<int>(sizeof defs / sizeof defs[0]); ++r) {+ t[static_cast<size_t>(partIdx(p, PRoute0 + 2 * r))].def = static_cast<float>(defs[r].src) / kSrcScale;+ t[static_cast<size_t>(partIdx(p, PRoute0 + 2 * r + 1))].def = static_cast<float>(defs[r].dst) / kDstScale;+ for (int sd = 0; sd < kSides; ++sd)+ t[static_cast<size_t>(sideIdx(p, sd, MatAmt0 + r))].def = 0.5f + 0.5f * defs[r].depth;+ }+ return t;+}++} // namespace++const std::vector<ParamInfo>& paramTable() {+ static const std::vector<ParamInfo> t = buildTable();+ return t;+}++} // namespace twin++namespace {++void putU32(std::vector<uint8_t>& b, uint32_t v) {+ for (int i = 0; i < 4; ++i) b.push_back(static_cast<uint8_t>(v >> (i * 8)));+}++uint32_t getU32(const uint8_t* p) {+ return static_cast<uint32_t>(p[0]) | static_cast<uint32_t>(p[1]) << 8 | static_cast<uint32_t>(p[2]) << 16 |+ static_cast<uint32_t>(p[3]) << 24;+}++} // namespace++Twin::Twin() {+ const auto& t = twin::paramTable();+ for (int i = 0; i < kNumParams; ++i) pn_[i].store(t[static_cast<size_t>(i)].def, std::memory_order_relaxed);+ // The effects (US5): one set per part, built and sized here so render never allocates.+ for (int p = 0; p < twin::kParts; ++p) {+ fx_[p][FxChorus] = std::make_unique<Chorus>();+ fx_[p][FxFlanger] = std::make_unique<Flanger>();+ fx_[p][FxPhaser] = std::make_unique<Phaser>();+ fx_[p][FxDelay] = std::make_unique<Delay>();+ fx_[p][FxReverb] = std::make_unique<Reverb>();+ fx_[p][FxDelay]->setParam(Delay::LinkLR, 1.0f); // one time for both sides; Ping-pong spreads it+ for (auto& d : fx_[p]) d->setSampleRate(44100.0, twin::kCtl);+ }+ patAuth_ = std::make_shared<twin::PatternSet>();+ publishPatterns();+ tele_[ScRecStep].store(-1.0f, std::memory_order_relaxed);+ tele_[ScLastKey].store(-1.0f, std::memory_order_relaxed);+ resetAll();+}++void Twin::setSampleRate(double sr) {+ sr = sr > 0 ? sr : 44100.0;+ sampleRate_.store(sr, std::memory_order_relaxed);+ for (auto& part : fx_)+ for (auto& d : part) d->setSampleRate(sr, twin::kCtl);+}++void Twin::setTransportInfo(const TransportInfo& ti) {+ for (auto& part : fx_)+ for (auto& d : part) d->setTransportInfo(ti);+}++std::string Twin::pluginParamId(int32_t i) const {+ return (i >= 0 && i < kNumParams) ? twin::paramTable()[static_cast<size_t>(i)].id : std::string();+}++std::string Twin::pluginParamName(int32_t i) const {+ return (i >= 0 && i < kNumParams) ? twin::paramTable()[static_cast<size_t>(i)].name : std::string();+}++float Twin::pluginParamDefault(int32_t i) const {+ return (i >= 0 && i < kNumParams) ? twin::paramTable()[static_cast<size_t>(i)].def : 0.0f;+}++std::string Twin::pluginParamText(int32_t i) const {+ if (i < 0 || i >= kNumParams) return {};+ const float v = pn_[i].load(std::memory_order_relaxed);+ // A matrix slot's source / destination reads as its name.+ for (int p = 0; p < twin::kParts; ++p) {+ const int r = i - twin::partIdx(p, twin::PRoute0);+ if (r >= 0 && r < 2 * twin::kRoutes)+ return r % 2 == 0 ? twin::srcName(twin::stepOf(v, twin::kSrcScale + 1))+ : twin::dstName(twin::stepOf(v, twin::kDstScale + 1));+ }+ // Generic readouts until the stories give each param its musical units.+ const auto& d = twin::paramTable()[static_cast<size_t>(i)];+ char buf[32];+ if (d.steps > 1) std::snprintf(buf, sizeof buf, "%d", static_cast<int>(std::lround(v * (d.steps - 1))) + 1);+ else std::snprintf(buf, sizeof buf, "%.0f%%", v * 100.0f);+ return buf;+}++int32_t Twin::pluginParamIndexOfId(const std::string& id) const {+ static const std::unordered_map<std::string, int32_t> index = [] {+ std::unordered_map<std::string, int32_t> m;+ const auto& t = twin::paramTable();+ m.reserve(t.size());+ for (size_t i = 0; i < t.size(); ++i) m.emplace(t[i].id, static_cast<int32_t>(i));+ return m;+ }();+ const auto it = index.find(id);+ return it == index.end() ? -1 : it->second;+}++// ---- voices -------------------------------------------------------------------------------++void Twin::computeStatics(int v) {+ pentad::Rng r;+ r.seed(pentad::hash32(0x7717u * 2654435761U + pentad::hash32(static_cast<uint32_t>(v) + 17U)));+ twin::Voice& V = voices_[v];+ V.oP[0] = r.bi();+ V.oP[1] = r.bi();+ V.oCut = r.bi();+ V.oEnv = r.bi();+}++void Twin::resetAll() {+ for (int v = 0; v < kMaxVoices; ++v) {+ twin::Voice& V = voices_[v];+ V = twin::Voice{};+ V.rng.seed(pentad::hash32(0x7717u ^ pentad::hash32(static_cast<uint32_t>(v) * 0x9E3779B9U + 1U)));+ V.noiseRng = pentad::hash32(static_cast<uint32_t>(v) + 0x51ED27u) | 1u;+ for (auto& l : V.lfo) l.rng.seed(V.rng.next());+ V.osc[0].ph = V.rng.uni();+ V.osc[1].ph = V.rng.uni();+ V.walkLeft = 1 + static_cast<int>(V.rng.next() % 4096u);+ computeStatics(v);+ }+ for (int p = 0; p < twin::kParts; ++p)+ for (int l = 0; l < 3; ++l) {+ glfo_[p][l] = twin::Lfo{};+ glfo_[p][l].rng.seed(pentad::hash32(0xA5A5u + static_cast<uint32_t>(l + 3 * p)));+ }+ heldN_[0] = heldN_[1] = 0;+ heldBits_[0] = heldBits_[1] = 0;+ for (auto& part : gLfoFade_)+ for (auto& f : part) f = 1.0f;+ fxHeld_[0] = fxHeld_[1] = false;+ orderCtr_ = 0;+ ctlLeft_ = 0;+ gexpr_.reset();+ seqNoteN_ = 0;+ transpose_ = transKeys_ = 0;+ arpN_ = arpKeys_ = 0;+ arpTook_[0] = arpTook_[1] = transTook_[0] = transTook_[1] = 0;+ pendPat_ = -1;+ freeRun_ = false; // all notes off ends a key-run sequence too+ freeT_ = 0.0;+ upperTail_ = false;+ upperQuiet_ = 0;+ patStartK_ = 0;+ playStep_ = -1;+ seqStepV_ = 0.0f;+ seqResync_ = true;+ for (auto& m : motion_) m = Motion{};+ for (auto& m : motionOvr_) m = twin::MotionOverride{};+ for (auto& part : dn_)+ for (auto& d : part) d.clear_buffers();+ // The effects start over too (a silent start or jump re-seeds everything, so renders repeat).+ for (auto& part : fx_) {+ part[FxChorus]->deviceAction(Chorus::A_Restart, 0, 0.0f);+ part[FxChorus]->deviceAction(Chorus::A_Clear, 0, 0.0f);+ part[FxFlanger]->deviceAction(Flanger::A_Restart, 0, 0.0f);+ part[FxFlanger]->deviceAction(Flanger::A_Clear, 0, 0.0f);+ part[FxPhaser]->deviceAction(Phaser::A_Restart, 0, 0.0f);+ part[FxPhaser]->deviceAction(Phaser::A_Clear, 0, 0.0f);+ part[FxDelay]->deviceAction(Delay::A_Reset, 0, 0.0f);+ part[FxReverb]->deviceAction(Reverb::A_Reset, 0, 0.0f);+ }+}++// Each part keeps its own stack of held keys (in the order played) for its mono fallback.+void Twin::pushHeld(int part, int note) {+ removeHeld(part, note);+ int* h = held_[part];+ int& n = heldN_[part];+ if (n == kMaxHeld) {+ std::memmove(h, h + 1, sizeof(int) * (kMaxHeld - 1));+ --n;+ }+ h[n++] = note;+}++void Twin::removeHeld(int part, int note) {+ int* h = held_[part];+ int& n = heldN_[part];+ for (int i = 0; i < n; ++i)+ if (h[i] == note) {+ std::memmove(h + i, h + i + 1, sizeof(int) * static_cast<size_t>(n - i - 1));+ --n;+ break;+ }+}++// ---- parts (US9) ---------------------------------------------------------------------------+// Single: the Lower part has every voice. Layer: both parts play every key. Split: keys below+// the split key go to Lower, the rest to Upper. In Layer and Split the voices are shared out —+// Lower takes `share` (2, 4 … 10), Upper the rest of the cap — and each part steals only from+// its own share.++int Twin::layoutMode() const { return twin::stepOf(get(twin::GMode), 3); }++Twin::Slice Twin::slice(int part) const {+ const int cap = voiceCap();+ if (layoutMode() == 0) return part == 0 ? Slice{0, cap} : Slice{0, 0};+ const int lo = std::clamp(2 + 2 * twin::stepOf(get(twin::GShare), 5), 2, cap - 2);+ return part == 0 ? Slice{0, lo} : Slice{lo, cap - lo};+}++int Twin::keyParts(int pitch, int* out) const {+ switch (layoutMode()) {+ case 1: out[0] = 0, out[1] = 1; return 2;+ case 2: out[0] = pitch < static_cast<int>(std::lround(get(twin::GSplitKey) * 127.0f)) ? 0 : 1; return 1;+ default: out[0] = 0; return 1;+ }+}++int Twin::seqParts(int* out) const {+ if (layoutMode() == 0) return out[0] = 0, 1;+ switch (twin::stepOf(get(twin::GSeqTarget), 3)) {+ case 1: out[0] = 1; return 1;+ case 2: out[0] = 0, out[1] = 1; return 2;+ default: out[0] = 0; return 1;+ }+}++// A free voice (least recently used), else the oldest releasing one, else the oldest of all+// with a steal fade (`fade` = true).+int Twin::allocate(int first, int count, bool& fade) {+ fade = false;+ int best = -1;+ uint64_t bo = ~0ull;+ for (int v = first; v < first + count; ++v)+ if (!voices_[v].active && voices_[v].pendNote < 0 && voices_[v].order < bo) bo = voices_[v].order, best = v;+ if (best >= 0) return best;+ for (int v = first; v < first + count; ++v)+ if (!voices_[v].gate && voices_[v].pendNote < 0 && voices_[v].order < bo) bo = voices_[v].order, best = v;+ if (best >= 0) return best;+ for (int v = first; v < first + count; ++v)+ if (voices_[v].pendNote < 0 && voices_[v].order < bo) bo = voices_[v].order, best = v;+ fade = true;+ return best >= 0 ? best : first;+}++void Twin::wakeVoice(twin::Voice& V) {+ V.active = true;+ V.fresh = true;+ for (auto& o : V.osc) {+ o.ph += V.rng.uni();+ o.ph -= std::floor(o.ph);+ o.hi = true;+ o.ring.clear();+ }+ V.o2Out = 0.0f;+ V.fx1[0] = V.fx1[1] = 0.0;+ V.fy1[0] = V.fy1[1] = 0.0f;+ V.noiseLp = 0.0f;+ V.mm.reset();+ V.ld.reset();+ V.ld.setInternalOversampling(1); // the voice already runs at ×2+ V.sat.reset();+ V.fb = 0.0f;+}++void Twin::startVoice(int v, int note, float vel, int s, int S, bool glide) {+ twin::Voice& V = voices_[v];+ const twin::PartCtl& c = ctl_[V.part];+ V.note = note;+ V.vel = vel;+ V.relVel = 0.0f;+ V.gate = true;+ V.seq = false;+ V.stackIdx = s;+ V.stackN = S;+ V.order = ++orderCtr_;+ const float u = S > 1 ? 2.0f * static_cast<float>(s) / static_cast<float>(S - 1) - 1.0f : 0.0f;+ V.stackU = u;+ V.pitchTgt = static_cast<float>(note);+ if (!V.hasPitch || !glide) V.pitch = V.pitchTgt;+ V.hasPitch = true;+ // Stereo position: the unison stack fans out; otherwise by voice or by key.+ float pos;+ if (S > 1) pos = u;+ else if (c.spreadMode == 1)+ pos = std::clamp((static_cast<float>(note) - 60.0f) / 30.0f, -1.0f, 1.0f);+ else+ pos = static_cast<float>((v * 7) % kMaxVoices) / static_cast<float>(kMaxVoices - 1) * 2.0f - 1.0f;+ V.panPos = pos; // voiceControl() turns it into the pan gains, and keeps them current+ // A global LFO restarts (Retrig) and fades in (Fade) from the first key of a phrase: no other+ // key of the part is down.+ bool first = true;+ for (const auto& W : voices_)+ if (&W != &V && W.gate && W.part == V.part) first = false;+ for (int l = 0; l < 3; ++l) {+ if (first && c.lfoGlobal[l]) {+ if (c.lfoRetrig[l]) glfo_[V.part][l].ph = 0.0;+ if (c.lfoFade[l] > 0.0f) gLfoFade_[V.part][l] = 0.0f;+ }+ if (c.lfoRetrig[l] && !c.lfoGlobal[l]) V.lfo[l].ph = 0.0;+ V.lfoFadeLvl[l] = c.lfoFade[l] > 0.0f ? 0.0f : 1.0f;+ V.lfoFadeInc[l] = c.lfoFade[l] > 0.0f ? static_cast<float>(1.0 / (c.lfoFade[l] * sr_)) : 0.0f;+ }+ if (!V.active) wakeVoice(V);+ V.fresh = true; // snap the ramps to this note's values+ V.ex.reset(c.exAdd);+ V.rnd = V.rng.bi();+ twin::voiceControl(V, c, sr_);+ V.fenv.gateOn(0);+ V.aenv.gateOn(0);+ V.menv.gateOn(static_cast<int32_t>(c.mDly * sr_));+}++void Twin::startPending(twin::Voice& V) {+ const int note = V.pendNote;+ V.pendNote = -1;+ V.fenv.lvl = V.aenv.lvl = V.menv.lvl = 0.0f;+ startVoice(static_cast<int>(&V - voices_), note, V.pendVel, V.pendStack, V.pendStackN, V.pendGlide);+ V.seq = V.pendSeq;+ for (int d = 0; d < kExprDims; ++d) V.ex.set(d, V.pendExpr[d], ctl_[V.part].exAdd);+}++void Twin::release(twin::Voice& V) {+ V.gate = false;+ V.fenv.gateOff();+ V.aenv.gateOff();+ V.menv.gateOff();+}++// ---- notes in: the keyboard, or the sequencer ----------------------------------------------++void Twin::noteOn(int32_t pitch, float velocity) {+ if (pitch < 0 || pitch > 127) return;+ wake();+ applyRate();+ if (!ctlInit_) updateControl(clockAt(0));+ const float vel = std::clamp(velocity, 0.0f, 1.0f);+ tele_[ScLastKey].store(static_cast<float>(pitch), std::memory_order_relaxed);+ if (recArmed_.load(std::memory_order_relaxed)) { // step record: the card turns these into steps+ const uint32_t h = ringHead_.load(std::memory_order_relaxed);+ if (h - ringTail_.load(std::memory_order_acquire) < kRing) {+ ring_[h % kRing].store(static_cast<uint32_t>(pitch) << 8 | static_cast<uint32_t>(std::lround(vel * 127.0f)), std::memory_order_relaxed);+ ringHead_.store(h + 1, std::memory_order_release);+ }+ }+ // Transport stopped: the first key held starts the sequencer (Consort-style); while it rolls,+ // the sequencer plays on the song's grid and the keys arpeggiate or transpose it.+ if (get(twin::GSeqOn) >= 0.5f && spb_ > 1.0 && !playing_ && (!freeRun_ || (arpKeys_ == 0 && transKeys_ == 0 && !seqLatched())))+ freeStart();+ if (seqActive()) {+ if (twin::stepOf(get(twin::GSeqKind), 2) == 1) { // the arpeggiator takes the keys+ if (get(twin::GArpHold) >= 0.5f && arpKeys_ == 0) arpN_ = 0; // a new chord replaces a held one+ if (arpN_ == 0) arpStartK_ = !playing_ && !seqRunning_ ? 0 : nextK_; // a free start counts from 0+ if (arpN_ < 32) arpList_[arpN_++] = pitch;+ if (!(arpTook_[pitch >> 6] & (uint64_t{1} << (pitch & 63)))) ++arpKeys_;+ arpTook_[pitch >> 6] |= uint64_t{1} << (pitch & 63);+ arpVel_ = vel;+ return;+ }+ if (get(twin::GSeqTranspose) >= 0.5f || !playing_) { // the key transposes the pattern from its first note+ int root = 60;+ if (const twin::PatternSet* ps = pats_.live()) {+ const twin::Pattern& P = ps->pat[curPat_];+ for (int i = 0; i < P.length; ++i)+ if (P.step[i].n > 0) { root = P.step[i].note[0]; break; }+ }+ transpose_ = get(twin::GSeqTranspose) >= 0.5f ? pitch - root : 0;+ if (!(transTook_[pitch >> 6] & (uint64_t{1} << (pitch & 63)))) ++transKeys_;+ transTook_[pitch >> 6] |= uint64_t{1} << (pitch & 63);+ return;+ }+ }+ keyOn(pitch, vel);+}++void Twin::noteOff(int32_t pitch) {+ if (pitch < 0 || pitch > 127) return;+ wake();+ if (recArmed_.load(std::memory_order_relaxed)) {+ const uint32_t h = ringHead_.load(std::memory_order_relaxed);+ if (h - ringTail_.load(std::memory_order_acquire) < kRing) {+ ring_[h % kRing].store(1u << 16 | static_cast<uint32_t>(pitch) << 8, std::memory_order_relaxed);+ ringHead_.store(h + 1, std::memory_order_release);+ }+ }+ // Only the keys the sequencer took are its releases; any other key plays the voices as usual.+ const uint64_t bit = uint64_t{1} << (pitch & 63);+ if (arpTook_[pitch >> 6] & bit) {+ arpTook_[pitch >> 6] &= ~bit;+ if (arpKeys_ > 0) {+ --arpKeys_;+ if (get(twin::GArpHold) < 0.5f) { // without Hold the arpeggio follows the keys+ int w = 0;+ for (int i = 0; i < arpN_; ++i)+ if (arpList_[i] != pitch) arpList_[w++] = arpList_[i];+ arpN_ = w;+ }+ }+ freeStop();+ return;+ }+ if (transTook_[pitch >> 6] & bit) {+ transTook_[pitch >> 6] &= ~bit;+ if (transKeys_ > 0 && --transKeys_ == 0 && get(twin::GSeqLatch) < 0.5f) transpose_ = 0;+ freeStop();+ return;+ }+ keyOff(pitch);+}++// The last key up stops a free-running sequence, unless Latch / Hold keeps it.+void Twin::freeStop() {+ if (freeRun_ && !playing_ && arpKeys_ == 0 && transKeys_ == 0 && !seqLatched()) freeRun_ = false;+}++// The release velocity reaches the key's sounding voices before they release (FR-030).+void Twin::noteOffVelocity(int32_t pitch, float velocity) {+ if (pitch < 0 || pitch > 127) return;+ for (auto& V : voices_)+ if (V.active && V.gate && !V.seq && V.note == pitch) V.relVel = std::clamp(velocity, 0.0f, 1.0f);+ noteOff(pitch);+}++void Twin::keyOn(int pitch, float vel) {+ heldBits_[pitch >> 6] |= uint64_t{1} << (pitch & 63);+ int parts[2];+ const int n = keyParts(pitch, parts);+ for (int i = 0; i < n; ++i) keyOnPart(parts[i], pitch, vel);+}++void Twin::keyOff(int pitch) {+ heldBits_[pitch >> 6] &= ~(uint64_t{1} << (pitch & 63));+ for (int p = 0; p < twin::kParts; ++p) keyOffPart(p, pitch);+}++void Twin::keyOnPart(int part, int pitch, float vel) {+ const twin::PartCtl& c = ctl_[part];+ const Slice sl = slice(part);+ if (sl.count <= 0) return;+ const bool othersHeld = heldN_[part] > 0;+ pushHeld(part, pitch);+ const bool glideOn = c.glideSec > 0.0f && (!c.glideLegato || othersHeld);+ if (c.voiceMode == 0) { // Poly+ int v = -1;+ for (int k = sl.first; k < sl.first + sl.count; ++k) // the same key again → retrigger its voice+ if (voices_[k].gate && voices_[k].note == pitch && voices_[k].pendNote < 0 && !voices_[k].seq) {+ v = k;+ break;+ }+ bool fade = false;+ if (v < 0) v = allocate(sl.first, sl.count, fade);+ twin::Voice& V = voices_[v];+ V.part = part;+ if (fade) {+ V.pendNote = pitch;+ V.pendVel = vel;+ V.pendStack = 0;+ V.pendStackN = 1;+ V.pendGlide = glideOn;+ V.pendSeq = false;+ for (int d = 0; d < kExprDims; ++d) V.pendExpr[d] = kExprNeutral[d];+ V.fade = fadeLen_;+ V.gate = false;+ } else+ startVoice(v, pitch, vel, 0, 1, glideOn);+ return;+ }+ // Mono / Legato / Unison: the last key wins; Legato and Unison glide without retriggering+ // while another key is held, Mono always retriggers.+ const int S = c.voiceMode == 3 ? sl.count : 1;+ if (!othersHeld || c.voiceMode == 1) {+ for (int s = 0; s < S; ++s) {+ voices_[sl.first + s].part = part;+ startVoice(sl.first + s, pitch, vel, s, S, glideOn);+ }+ return;+ }+ for (int s = 0; s < S; ++s) {+ twin::Voice& V = voices_[sl.first + s];+ V.note = pitch;+ V.pitchTgt = static_cast<float>(pitch);+ if (!glideOn) V.pitch = V.pitchTgt;+ }+}++void Twin::keyOffPart(int part, int pitch) {+ bool wasHeld = false;+ for (int i = 0; i < heldN_[part]; ++i) wasHeld |= held_[part][i] == pitch;+ removeHeld(part, pitch);+ const twin::PartCtl& c = ctl_[part];+ const Slice sl = slice(part);+ if (c.voiceMode == 0 || sl.count <= 0) {+ for (auto& V : voices_) {+ if (V.part != part) continue;+ if (V.gate && V.note == pitch && !V.seq) release(V);+ if (V.pendNote == pitch && !V.pendSeq) V.pendNote = -1; // ended before its steal fade finished+ }+ return;+ }+ if (!wasHeld) return;+ const int S = c.voiceMode == 3 ? sl.count : 1;+ if (heldN_[part] == 0) {+ for (int s = 0; s < S; ++s)+ if (voices_[sl.first + s].gate && !voices_[sl.first + s].seq) release(voices_[sl.first + s]);+ return;+ }+ const int back = held_[part][heldN_[part] - 1]; // fall back to the last key still held+ for (int s = 0; s < S; ++s) {+ twin::Voice& V = voices_[sl.first + s];+ if (!V.active) continue;+ V.note = back;+ V.pitchTgt = static_cast<float>(back);+ if (c.glideSec <= 0.0f) V.pitch = V.pitchTgt;+ }+}++// A sequencer note: like a key, but outside the held-key stack, and released only by the+// sequencer. It plays on the parts seq.target names. In the mono modes the last note wins.+void Twin::seqOn(int pitch, float vel) {+ int parts[2];+ const int np = seqParts(parts);+ for (int i = 0; i < np; ++i) {+ const int part = parts[i];+ const twin::PartCtl& c = ctl_[part];+ const Slice sl = slice(part);+ if (sl.count <= 0) continue;+ if (c.voiceMode == 0) {+ bool fade = false;+ const int v = allocate(sl.first, sl.count, fade);+ twin::Voice& V = voices_[v];+ V.part = part;+ if (fade) {+ V.pendNote = pitch;+ V.pendVel = vel;+ V.pendStack = 0;+ V.pendStackN = 1;+ V.pendGlide = false;+ V.pendSeq = true;+ for (int d = 0; d < kExprDims; ++d) V.pendExpr[d] = kExprNeutral[d];+ V.fade = fadeLen_;+ V.gate = false;+ } else {+ startVoice(v, pitch, vel, 0, 1, false);+ V.seq = true;+ }+ continue;+ }+ const int S = c.voiceMode == 3 ? sl.count : 1;+ const bool legato = seqNoteN_ > 1 && c.voiceMode != 1;+ for (int s = 0; s < S; ++s) {+ twin::Voice& V = voices_[sl.first + s];+ V.part = part;+ if (legato && V.gate) {+ V.note = pitch;+ V.pitchTgt = static_cast<float>(pitch);+ if (c.glideSec <= 0.0f) V.pitch = V.pitchTgt;+ } else+ startVoice(sl.first + s, pitch, vel, s, S, c.glideSec > 0.0f);+ V.seq = true;+ }+ }+}++void Twin::seqOff(int pitch) {+ for (auto& V : voices_) {+ if (V.gate && V.seq && V.note == pitch) release(V);+ if (V.pendNote == pitch && V.pendSeq) V.pendNote = -1;+ }+}++void Twin::allNotesOff() {+ resetAll();+}++// ---- the sequencer (US8) -------------------------------------------------------------------+// Steps sit on a grid counted from the song's start (AR-9: the transport is the only clock), so a+// step's sample is the same however the host splits its blocks; a pattern's step is that index+// modulo its length. Odd steps lean late by the swing. While the transport is stopped the+// sequencer is silent and the keys play the instrument as usual.++bool Twin::seqActive() const {+ return get(twin::GSeqOn) >= 0.5f && spb_ > 1.0 && (playing_ || freeRun_);+}++// Latch (Seq) or Hold (Arp): the sequence keeps running after the keys are up.+bool Twin::seqLatched() const {+ return twin::stepOf(get(twin::GSeqKind), 2) == 1 ? get(twin::GArpHold) >= 0.5f : get(twin::GSeqLatch) >= 0.5f;+}++// A key with the transport stopped starts the sequencer on its own clock, from its first step.+void Twin::freeStart() {+ releaseSeqNotes();+ seqRunning_ = false; // seqService re-syncs: pattern, first step, motion+ seqResync_ = true;+ freeRun_ = true;+ freeT_ = 0.0;+ arpN_ = 0;+ arpStartK_ = 0;+}++double Twin::stepBeats() const {+ static constexpr double kRates[6] = {1.0, 0.5, 1.0 / 3.0, 0.25, 1.0 / 6.0, 0.125}; // 1/4 1/8 1/8T 1/16 1/16T 1/32+ return kRates[twin::stepOf(get(twin::GSeqRate), 6)];+}++double Twin::onsetSample(int64_t k) const {+ const double swing = (k & 1) ? get(twin::GSeqSwing) * 0.5 * seqStepBeats_ : 0.0;+ return std::ceil(((static_cast<double>(k) * seqStepBeats_) + swing) * spb_ - 1e-6);+}++void Twin::releaseSeqNotes() {+ for (int i = 0; i < seqNoteN_; ++i) seqOff(seqNotes_[i].pitch);+ seqNoteN_ = 0;+}++int Twin::seqService(int offset) {+ freeStop(); // Latch / Hold switched off with no key down ends a key-run sequence+ if (!seqActive()) {+ if (seqRunning_) {+ releaseSeqNotes();+ seqRunning_ = false;+ playStep_ = -1;+ for (auto& m : motion_) m.set = false;+ }+ return INT32_MAX;+ }+ const double now = clockAt(offset); // absolute sample: the song's, or the free clock's+ const double sb = stepBeats();+ if (seqResync_ || sb != seqStepBeats_ || !seqRunning_) {+ if (seqResync_) releaseSeqNotes();+ seqStepBeats_ = sb;+ nextK_ = static_cast<int64_t>(std::ceil(now / spb_ / sb - 1e-9));+ while (onsetSample(nextK_) < now) ++nextK_;+ if (!seqRunning_) {+ curPat_ = twin::stepOf(get(twin::GSeqPattern), twin::kPatterns);+ pendPat_ = -1;+ patStartK_ = 0; // a pattern started from stopped sits on the song's grid+ }+ seqResync_ = false;+ seqRunning_ = true;+ }+ // Note-offs that are due, then the steps that are.+ for (int i = 0; i < seqNoteN_;)+ if (!seqNotes_[i].tie && seqNotes_[i].off <= now) {+ seqOff(seqNotes_[i].pitch);+ seqNotes_[i] = seqNotes_[--seqNoteN_];+ } else+ ++i;+ while (onsetSample(nextK_) <= now) {+ fireStep(nextK_, onsetSample(nextK_));+ ++nextK_;+ }+ double next = onsetSample(nextK_);+ for (int i = 0; i < seqNoteN_; ++i)+ if (!seqNotes_[i].tie) next = std::min(next, seqNotes_[i].off);+ return std::max(1, static_cast<int>(std::ceil(next - now)));+}++void Twin::fireStep(int64_t k, double onset) {+ const twin::PatternSet* ps = pats_.live();+ if (!ps) return;+ const double stepLen = seqStepBeats_ * spb_;+ int notes[twin::kStepNotes];+ int n = 0;+ float vel = 0.8f;+ double off = onset + 0.5 * stepLen;+ bool tie = false;+ const int want = twin::stepOf(get(twin::GSeqPattern), twin::kPatterns);+ pendPat_ = want == curPat_ ? -1 : want; // switches at the pattern's end; picking the playing one cancels+ if (twin::stepOf(get(twin::GSeqKind), 2) == 1) {+ // The arpeggiator: the held (or held-over) chord, one note — or all of it — per step.+ n = twin::arpNotes(arpList_, arpN_, twin::stepOf(get(twin::GArpMode), twin::kArpModes),+ 1 + twin::stepOf(get(twin::GArpOct), 4), k - arpStartK_, 0x5EEDu, notes, twin::kStepNotes);+ vel = arpVel_;+ off = onset + std::max(0.05, static_cast<double>(get(twin::GArpGate))) * stepLen;+ playStep_ = arpN_ > 0 ? static_cast<int>((k - arpStartK_) % 64) : -1;+ for (auto& m : motion_) m.set = false; // the arpeggiator has no motion: the knobs are back+ seqStepV_ = 0.0f;+ } else {+ auto stepIn = [&](const twin::Pattern& P) {+ const int64_t r = k - patStartK_;+ return static_cast<int>(((r % P.length) + P.length) % P.length);+ };+ const twin::Pattern* P = &ps->pat[curPat_];+ int st = stepIn(*P);+ if (st == 0 && pendPat_ >= 0) {+ curPat_ = pendPat_;+ pendPat_ = -1;+ patStartK_ = k; // the queued pattern starts on its first step, whatever its length+ P = &ps->pat[curPat_];+ st = 0;+ }+ playStep_ = st;+ seqStepV_ = P->length > 1 ? static_cast<float>(st) / static_cast<float>(P->length - 1) : 0.0f;+ const twin::Step& S = P->step[st];+ for (int i = 0; i < S.n; ++i) notes[n++] = std::clamp(S.note[i] + transpose_, 0, 127);+ vel = S.vel / 127.0f;+ tie = S.gate >= twin::kGateTie;+ off = onset + (tie ? stepLen : S.gate * 0.01 * stepLen);+ // Motion lanes: this step's values (a smooth lane glides on to the next step's).+ for (int l = 0; l < twin::kLanes; ++l) {+ const twin::Lane& L = P->lane[l];+ Motion& M = motion_[l];+ M.set = L.target >= 0 && L.val[st] != twin::kMotionUnset;+ if (!M.set) continue;+ M.target = L.target;+ M.from = L.val[st] / 65534.0f;+ const uint16_t nx = L.val[(st + 1) % P->length];+ M.to = nx == twin::kMotionUnset ? M.from : nx / 65534.0f;+ M.smooth = L.smooth != 0;+ M.t0 = onset;+ M.len = stepLen;+ }+ }+ // Tied notes that come back are held over; the rest of the last step's notes end here.+ for (int i = 0; i < seqNoteN_;) {+ SeqNote& sn = seqNotes_[i];+ bool again = false;+ for (int j = 0; j < n; ++j)+ if (notes[j] == sn.pitch) again = true;+ if (sn.tie && again) {+ for (int j = 0; j < n; ++j)+ if (notes[j] == sn.pitch) notes[j] = -1; // already sounding+ sn.off = off;+ sn.tie = tie;+ ++i;+ } else if (sn.tie || sn.off <= onset || again) {+ // A note still sounding (a long gate swung past this onset) that this step plays again+ // ends here, so its own note-off can't cut the new one short.+ seqOff(sn.pitch);+ sn = seqNotes_[--seqNoteN_];+ } else+ ++i;+ }+ for (int j = 0; j < n; ++j) {+ if (notes[j] < 0 || seqNoteN_ >= 32) continue;+ seqOn(notes[j], vel);+ seqNotes_[seqNoteN_++] = {notes[j], off, tie};+ }+}++++void Twin::noteExpression(int32_t pitch, int32_t dim, float value) {+ if (pitch < 0) {+ gexpr_.set(dim, value); // takes effect at the next control interval, through exAdd+ return;+ }+ if (dim < 0 || dim >= kExprDims) return;+ for (auto& V : voices_) {+ if (V.gate && V.note == pitch && V.pendNote < 0) V.ex.set(dim, value, ctl_[V.part].exAdd);+ if (V.pendNote == pitch) V.pendExpr[dim] = value; // its voice is still fading out+ }+}++void Twin::controller(int32_t ctl, float value) {+ if (ctl == 1) modWheel_ = std::clamp(value, 0.0f, 1.0f);+ else Instrument::controller(ctl, value);+}++void Twin::setTransport(double beatStart, double samplesPerBeat, bool playing) {+ // Whole samples: the sequencer's step times are whole samples too, so a block boundary that+ // lands a hair off one can't move a step by a sample (renders repeat at any block size).+ const double pos = std::round(beatStart * samplesPerBeat);+ const bool jumped = playing && playing_ && std::fabs(pos - (tPos_ + tFrames_)) > 2.0;+ if (jumped || playing != playing_) seqResync_ = true;+ if ((jumped || (playing && !playing_))) {+ bool any = false;+ for (const auto& V : voices_) any |= V.active;+ if (!any) resetAll(); // a silent start or jump re-seeds: renders repeat exactly+ wake();+ }+ for (auto& part : fx_)+ for (auto& d : part) d->setTransport(beatStart, samplesPerBeat, playing);+ beat_ = beatStart;+ spb_ = samplesPerBeat;+ tPos_ = pos;+ tFrames_ = 0.0;+ // Stopping with keys still held carries on on the free clock; starting hands over to the song.+ if (playing_ && !playing) {+ freeRun_ = arpKeys_ > 0 || transKeys_ > 0;+ freeT_ = 0.0;+ } else if (playing)+ freeRun_ = false;+ playing_ = playing;+}++// ---- render ------------------------------------------------------------------------------++// A patch-wide source's value (the same for every voice of the part).+float Twin::globalValue(int part, const twin::PartCtl& c, int src) const {+ using namespace twin;+ // The pad, or a motion lane playing it (FR-063).+ auto pad = [&](int g) { const float o = motionOvr_[part].pad[g - GPadX]; return o >= 0.0f ? o : get(g); };+ auto bip = [&](int g) { return (pad(g) - 0.5f) * 2.0f; };+ switch (src) {+ case SrcLfo1: return glfo_[part][0].val * gLfoFade_[part][0] * c.lfoAmt[0];+ case SrcLfo2: return glfo_[part][1].val * gLfoFade_[part][1] * c.lfoAmt[1];+ case SrcLfo3: return glfo_[part][2].val * gLfoFade_[part][2] * c.lfoAmt[2];+ case SrcModWheel: return modWheel_;+ case SrcPitchWheel: return gexpr_.wheel;+ case SrcPadX: return bip(GPadX);+ case SrcPadY: return bip(GPadY);+ case SrcPadZ: return pad(GPadZ);+ default:+ if (src >= SrcMacro1 && src < SrcMacro1 + kMacros) return get(partIdx(part, PMacro0 + src - SrcMacro1));+ return 0.0f;+ case SrcSeqGate: return seqRunning_ && seqNoteN_ > 0 ? 1.0f : 0.0f; // a step's notes are sounding+ case SrcSeqStep: return seqRunning_ ? seqStepV_ : 0.0f;+ }+}++// A per-note source's value for one voice.+float Twin::sourceValue(const twin::Voice& V, const twin::PartCtl& c, int src) const {+ using namespace twin;+ auto lfo = [&](int l) { return V.lfo[l].val * V.lfoFadeLvl[l] * c.lfoAmt[l]; };+ switch (src) {+ case SrcLfo1: return lfo(0);+ case SrcLfo2: return lfo(1);+ case SrcLfo3: return lfo(2);+ case SrcFiltEnv: return V.fenv.lvl;+ case SrcAmpEnv: return V.aenv.lvl;+ case SrcModEnv: return V.menv.lvl * (1.0f - c.mVel * (1.0f - V.vel));+ case SrcVelocity: return V.vel;+ case SrcKey: return std::clamp((static_cast<float>(V.note) - 60.0f) / 60.0f, -1.0f, 1.0f);+ case SrcPressure: return V.ex.pressure();+ case SrcSlide: return V.ex.slide();+ case SrcBend: return std::clamp(V.ex.bend() / kRoutePitchSt, -1.0f, 1.0f);+ case SrcRandom: return V.rnd;+ case SrcRelVelocity: return V.relVel;+ default: return 0.0f;+ }+}++namespace {++// A source that is the same for every voice of a part: its routes act on the whole part.+bool globalSource(int src, const twin::PartCtl& c) {+ using namespace twin;+ switch (src) {+ case SrcLfo1: return c.lfoGlobal[0];+ case SrcLfo2: return c.lfoGlobal[1];+ case SrcLfo3: return c.lfoGlobal[2];+ case SrcModWheel:+ case SrcPitchWheel:+ case SrcPadX:+ case SrcPadY:+ case SrcPadZ:+ case SrcSeqGate:+ case SrcSeqStep: return true;+ default: return src >= SrcMacro1 && src < SrcMacro1 + kMacros;+ }+}++// The effect controls a route can reach, as bits (per-note routes onto the part's effects).+enum FxField : uint32_t {+ FxModRate = 1, FxModDepth = 2, FxModMix = 4, FxDlyTime = 8, FxDlyFb = 16, FxDlyMix = 32,+ FxRevSize = 64, FxRevDamp = 128, FxRevMix = 256+};+uint32_t fxFieldOf(int side) {+ using namespace twin;+ switch (side) {+ case ModFxRate: return FxModRate;+ case ModFxDepth: return FxModDepth;+ case ModFxMix: return FxModMix;+ case DlyTime: return FxDlyTime;+ case DlyFb: return FxDlyFb;+ case DlyMix: return FxDlyMix;+ case RevSize: return FxRevSize;+ case RevDamp: return FxRevDamp;+ case RevMix: return FxRevMix;+ default: return 0;+ }+}++// One route's amount onto the offsets: a side param, the two pitches or the vibrato.+void addRoute(const twin::Dst& d, float x, float* off, float* pitch, float& vib) {+ using namespace twin;+ switch (d.kind) {+ case DstPitch: pitch[0] += x * kRoutePitchSt, pitch[1] += x * kRoutePitchSt; break;+ case DstPitch1: pitch[0] += x * kRoutePitchSt; break;+ case DstPitch2: pitch[1] += x * kRoutePitchSt; break;+ case DstVibrato: vib += x * kRouteVibratoSt; break;+ case DstSide: off[d.side] += x; break;+ default: break;+ }+}++} // namespace++// The part's routes from patch-wide sources, once per interval: offsets the part's PartCtl and+// every voice of it start from. The routes to Morph go first, at the knob's morph; the rest are+// weighed at the morph that gives, so a route that lives only on B starts as the part reaches B.+void Twin::partModulation(int part, float morph) {+ using namespace twin;+ const PartCtl& c = ctl_[part];+ float* off = partOff_[part];+ std::fill(off, off + kSideN, 0.0f);+ partMorphOff_[part] = partVib_[part] = partPitch_[part][0] = partPitch_[part][1] = 0.0f;+ bool any = false;+ for (int i = 0; i < routeN_[part]; ++i) {+ const LiveRoute& r = routes_[part][i];+ if (dstAt(r.dst).kind != DstMorph || !globalSource(r.src, c)) continue;+ const float x = r.at(morph) * globalValue(part, c, r.src);+ if (x == 0.0f) continue;+ partMorphOff_[part] += x;+ any = true;+ }+ const float pm = std::clamp(morph + partMorphOff_[part], 0.0f, 1.0f);+ for (int i = 0; i < routeN_[part]; ++i) {+ const LiveRoute& r = routes_[part][i];+ const Dst d = dstAt(r.dst);+ if (d.kind == DstMorph || !globalSource(r.src, c)) continue;+ const float x = r.at(pm) * globalValue(part, c, r.src);+ if (x == 0.0f) continue;+ any = true;+ addRoute(d, x, off, partPitch_[part], partVib_[part]);+ }+ partHasOff_[part] = any;+}++// One voice's routes from its own sources (envelopes, LFOs, velocity, key, expression, random):+// when any moves something, the voice evaluates its own values from the part's offsets plus its own.+// Its routes to Morph go first (at the knob's morph). When they move this voice's morph away from+// the part's, every other route — the part's patch-wide ones too — is weighed again at the voice's.+void Twin::modulateVoice(twin::Voice& V, float morph, const twin::LiveRoute* routes, int n) {+ using namespace twin;+ const PartCtl& pc = ctl_[V.part];+ const PartCtl& cur = V.hasOwn ? V.own : pc; // this voice's LFO rates and fades last interval+ const int p = V.part;+ float mo = 0.0f;+ for (int i = 0; i < n; ++i) {+ if (dstAt(routes[i].dst).kind != DstMorph || globalSource(routes[i].src, pc)) continue;+ mo += routes[i].at(morph) * sourceValue(V, cur, routes[i].src);+ }+ const float pm = std::clamp(morph + partMorphOff_[p], 0.0f, 1.0f);+ const float vm = std::clamp(morph + partMorphOff_[p] + mo, 0.0f, 1.0f);+ const bool own = vm != pm; // the voice sounds another morph: the part's offsets don't hold+ float pitch[2] = {own ? 0.0f : partPitch_[p][0], own ? 0.0f : partPitch_[p][1]};+ float vib = own ? 0.0f : partVib_[p];+ bool any = mo != 0.0f, sideAny = false;+ if (own) {+ std::fill(modOff_, modOff_ + kSideN, 0.0f);+ sideAny = true;+ }+ for (int i = 0; i < n; ++i) {+ const LiveRoute& r = routes[i];+ const Dst d = dstAt(r.dst);+ if (d.kind == DstMorph) continue;+ const bool global = globalSource(r.src, pc);+ if (global && !own) continue; // already in the part's values+ const float x = r.at(vm) * (global ? globalValue(p, pc, r.src) : sourceValue(V, cur, r.src));+ if (x == 0.0f) continue;+ any = true;+ if (d.kind == DstSide && !sideAny) {+ std::copy(partOff_[p], partOff_[p] + kSideN, modOff_);+ sideAny = true;+ }+ addRoute(d, x, modOff_, pitch, vib);+ }+ V.morphOff = mo;+ V.hasOwn = any;+ if (!any) return;+ evalPart(pn_, p, vm, spb_, sr_, V.own,+ sideAny ? modOff_ : (partHasOff_[p] ? partOff_[p] : nullptr), motionOvr_[p].n > 0 ? &motionOvr_[p] : nullptr);+ std::copy(pc.exAdd, pc.exAdd + kExprDims, V.own.exAdd); // expression is the part's, not a side's+ V.own.exCoef = pc.exCoef;+ V.own.semi[0] += pitch[0];+ V.own.semi[1] += pitch[1];+ V.own.vibExtra = vib;+}++// The part's effect values onto its devices (normalized params, smoothed by the devices).+void Twin::pushFx(int part) {+ const twin::PartCtl& c = ctl_[part];+ auto& fx = fx_[part];+ Device* mod = fx[c.modType == 1 ? FxFlanger : c.modType == 2 ? FxPhaser : FxChorus].get();+ if (mod == fx[FxChorus].get()) {+ mod->setParam(Chorus::Mode, c.modType == 3 ? 0.5f : 0.0f); // Classic, or Ensemble+ mod->setParam(Chorus::Rate, c.modRate);+ mod->setParam(Chorus::Amount, c.modDepth);+ mod->setParam(Chorus::Mix, c.modMix);+ } else if (mod == fx[FxFlanger].get()) {+ mod->setParam(Flanger::Rate, c.modRate);+ mod->setParam(Flanger::Depth, c.modDepth);+ mod->setParam(Flanger::Mix, c.modMix);+ } else {+ mod->setParam(Phaser::Rate, c.modRate);+ mod->setParam(Phaser::Depth, c.modDepth);+ mod->setParam(Phaser::Mix, c.modMix);+ }+ Device* dl = fx[FxDelay].get();+ dl->setParam(Delay::SyncMode, c.dlySync ? 1.0f : 0.0f);+ dl->setParam(Delay::TimeL, c.dlyTime);+ dl->setParam(Delay::TimeR, c.dlyTime);+ dl->setParam(Delay::DivL, c.dlyDiv);+ dl->setParam(Delay::DivR, c.dlyDiv);+ dl->setParam(Delay::Feedback, c.dlyFb);+ dl->setParam(Delay::PingPong, c.dlyPing ? 1.0f : 0.0f);+ dl->setParam(Delay::DryWet, c.dlyMix);+ Device* rv = fx[FxReverb].get();+ rv->setParam(Reverb::Size, c.revSize);+ rv->setParam(Reverb::Decay, 0.15f + 0.8f * c.revSize);+ rv->setParam(Reverb::HFDamp, c.revDamp);+ rv->setParam(Reverb::DryWet, c.revMix);+}++void Twin::updateControl(double now) {+ using namespace twin;+ ctlInit_ = true;+ static constexpr float kBendRanges[4] = {2.0f, 5.0f, 12.0f, 24.0f};+ const float bendRange = kBendRanges[stepOf(get(GBendRange), 4)];+ const int layout = layoutMode();+ const int parts = layout == 0 ? 1 : 2;+ const int recLane = recLane_.load(std::memory_order_relaxed);+ for (int part = 0; part < parts; ++part) {+ // The sequencer's motion lanes (paused on a lane that is recording): this interval's values.+ MotionOverride& mo = motionOvr_[part];+ mo = MotionOverride{};+ if (seqRunning_)+ for (int l = 0; l < kLanes; ++l) {+ const Motion& M = motion_[l];+ if (!M.set || l == recLane) continue;+ const float t = M.smooth ? static_cast<float>(std::clamp((now - M.t0) / M.len, 0.0, 1.0)) : 0.0f;+ const float v = M.from + (M.to - M.from) * t;+ if (M.target == partIdx(part, PMorph)) mo.morph = v;+ if (M.target >= GPadX && M.target <= GPadZ) mo.pad[M.target - GPadX] = v;+ for (int sd = 0; sd < kSides; ++sd) {+ const int s0 = sideIdx(part, sd, 0);+ if (M.target >= s0 && M.target < s0 + kSideN && mo.n < 4) {+ mo.side[mo.n] = sd;+ mo.param[mo.n] = M.target - s0;+ mo.v[mo.n++] = v;+ }+ }+ }+ const MotionOverride* ovr = mo.n > 0 ? &mo : nullptr;+ const float morph = mo.morph >= 0.0f ? mo.morph : partMorph(pn_, part);+ morphNow_[part] = morph;+ PartCtl& c = ctl_[part];+ evalPart(pn_, part, morph, spb_, sr_, c, nullptr, ovr);+ routeN_[part] = liveRoutes(pn_, part, routes_[part]);+ partModulation(part, morph);+ c.vibExtra = 0.0f; // a route that stopped (the pad let go, the route removed) leaves none+ if (partHasOff_[part]) {+ evalPart(pn_, part, std::clamp(morph + partMorphOff_[part], 0.0f, 1.0f), spb_, sr_, c, partOff_[part], ovr);+ c.semi[0] += partPitch_[part][0];+ c.semi[1] += partPitch_[part][1];+ c.vibExtra = partVib_[part];+ }+ gexpr_.offsets(bendRange, c.exAdd);+ c.exCoef = exprSmoothCoef(sr_);+ }+ // Structural changes release (never cut) what no longer fits: a new layout, voice share or+ // cap releases everything; a part's new voice mode releases that part.+ const int cap = voiceCap();+ const int shape = layout * 1000 + stepOf(get(GShare), 5) * 100 + cap;+ if (lastLayout_ >= 0 && (shape != lastLayout_ || cap < lastCap_)) {+ for (auto& V : voices_)+ if (V.gate) release(V);+ heldN_[0] = heldN_[1] = 0;+ }+ // Back to Single: the Upper part's voices were released above (never cut); it goes on+ // rendering — voices and effects — until its tail is quiet (renderSegment), then stops.+ if (parts == 1) {+ for (auto& V : voices_)+ if (V.active && V.part != 0) {+ V.pendNote = -1;+ upperTail_ = true;+ }+ } else+ upperTail_ = false;+ for (int part = 0; part < kParts; ++part) {+ const int vm = ctl_[part].voiceMode;+ if (part < parts && lastMode_[part] >= 0 && vm != lastMode_[part]) {+ for (auto& V : voices_)+ if (V.gate && V.part == part) release(V);+ heldN_[part] = 0;+ }+ lastMode_[part] = vm;+ }+ lastLayout_ = shape;+ lastCap_ = cap;+ // A global LFO's fade-in (all three: LFO 1 feeds the matrix too).+ for (int part = 0; part < parts; ++part)+ for (int l = 0; l < 3; ++l) {+ const PartCtl& pc = ctl_[part];+ float& f = gLfoFade_[part][l];+ f = pc.lfoGlobal[l] && pc.lfoFade[l] > 0.0f ? std::min(1.0f, f + static_cast<float>(kCtl / (pc.lfoFade[l] * sr_))) : 1.0f;+ }+ // The LFOs that only feed the matrix move once per interval (LFO 1 runs per sample, for vibrato).+ for (int part = 0; part < parts; ++part)+ for (int l = 1; l < 3; ++l)+ if (ctl_[part].lfoGlobal[l])+ glfo_[part][l].step(ctl_[part].lfoHz[l] / sr_ * kCtl, ctl_[part].lfoShape[l], ctl_[part].lfoSym[l], ctl_[part].lfoCurve[l]);+ for (auto& V : voices_) {+ if (!V.active) continue;+ const PartCtl& vc = V.hasOwn ? V.own : ctl_[V.part];+ for (int l = 1; l < 3; ++l) {+ if (!vc.lfoGlobal[l]) V.lfo[l].step(vc.lfoHz[l] / sr_ * kCtl, vc.lfoShape[l], vc.lfoSym[l], vc.lfoCurve[l]);+ if (V.lfoFadeLvl[l] < 1.0f) V.lfoFadeLvl[l] = std::min(1.0f, V.lfoFadeLvl[l] + V.lfoFadeInc[l] * kCtl);+ }+ modulateVoice(V, morphNow_[V.part], routes_[V.part], routeN_[V.part]);+ voiceControl(V, V.hasOwn ? V.own : ctl_[V.part], sr_);+ }+ // The effects are one per part: a route from a per-note source (velocity, an envelope…) to an+ // effect control follows the newest note of the part, as on a poly synth's global destinations.+ for (int part = 0; part < parts; ++part) {+ PartCtl& c = ctl_[part];+ if (!c.fxOn) continue;+ uint32_t mask = 0;+ for (int i = 0; i < routeN_[part]; ++i) {+ const LiveRoute& r = routes_[part][i];+ const Dst d = dstAt(r.dst);+ if (d.kind == DstSide && !globalSource(r.src, c)) mask |= fxFieldOf(d.side);+ }+ // The newest sounding note sets them, and they stay where it left them once every note is+ // gone (an effect's tail keeps the last note's mix).+ const Voice* newest = nullptr;+ if (mask != 0)+ for (const auto& V : voices_)+ if (V.active && V.part == part && V.hasOwn && (!newest || V.order > newest->order)) newest = &V;+ if (newest) fxHold_[part] = newest->own, fxHeld_[part] = true;+ if (mask == 0) fxHeld_[part] = false;+ if (fxHeld_[part]) {+ const PartCtl& o = fxHold_[part];+ if (mask & FxModRate) c.modRate = o.modRate;+ if (mask & FxModDepth) c.modDepth = o.modDepth;+ if (mask & FxModMix) c.modMix = o.modMix;+ if (mask & FxDlyTime) c.dlyTime = o.dlyTime;+ if (mask & FxDlyFb) c.dlyFb = o.dlyFb;+ if (mask & FxDlyMix) c.dlyMix = o.dlyMix;+ if (mask & FxRevSize) c.revSize = o.revSize;+ if (mask & FxRevDamp) c.revDamp = o.revDamp;+ if (mask & FxRevMix) c.revMix = o.revMix;+ }+ pushFx(part);+ }+ // LFO 1 in global mode: this interval's values, per part.+ for (int part = 0; part < parts; ++part)+ if (ctl_[part].lfoGlobal[0]) {+ Lfo& L = glfo_[part][0];+ const double inc = ctl_[part].lfoHz[0] / sr_;+ for (int i = 0; i < kCtl; ++i) gLfo1_[part][i] = L.step(inc, ctl_[part].lfoShape[0]);+ }+}++void Twin::renderSegment(float* out, int n) {+ const int os = os_;+ int active = 0;+ float pk = blockPeak_;+ const int parts = layoutMode() != 0 || upperTail_ ? 2 : 1;+ for (int part = 0; part < parts; ++part) {+ const float* lfo1 = gLfo1_[part] + (twin::kCtl - ctlLeft_);+ std::fill(osL_, osL_ + n * os, 0.0f);+ std::fill(osR_, osR_ + n * os, 0.0f);+ bool sounding = false;+ for (auto& V : voices_) {+ if (!V.active || V.part != part) continue;+ int k = 0;+ while (k < n) {+ k = twin::renderVoice(V, V.hasOwn ? V.own : ctl_[V.part], k, n, os, sr_, modWheel_, fadeLen_, lfo1, osL_, osR_);+ if (k >= n) break;+ if (V.active && V.fade == 0 && V.pendNote >= 0) startPending(V);+ else break;+ }+ sounding = true;+ active += V.active ? 1 : 0;+ }+ if (os == 2) {+ dn_[part][0].process_block(dsL_, osL_, n);+ dn_[part][1].process_block(dsR_, osR_, n);+ } else {+ std::copy(osL_, osL_ + n, dsL_);+ std::copy(osR_, osR_ + n, dsR_);+ }+ for (int i = 0; i < n; ++i) {+ fxBuf_[2 * i] = dsL_[i] * kOutGain;+ fxBuf_[2 * i + 1] = dsR_[i] * kOutGain;+ }+ // The part's effects: Mod FX ▸ Delay ▸ Reverb. One switched on starts from silence.+ const twin::PartCtl& c = ctl_[part];+ const bool on[kFxN] = {c.fxOn && c.modOn && (c.modType == 0 || c.modType == 3), c.fxOn && c.modOn && c.modType == 1,+ c.fxOn && c.modOn && c.modType == 2, c.fxOn && c.dlyOn, c.fxOn && c.revOn};+ for (int f = 0; f < kFxN; ++f) {+ if (!on[f]) {+ fxWasOn_[part][f] = false;+ continue;+ }+ if (!fxWasOn_[part][f]) {+ static constexpr int kClear[kFxN] = {Chorus::A_Clear, Flanger::A_Clear, Phaser::A_Clear, Delay::A_ClearLoop, Reverb::A_KillTail};+ fx_[part][f]->deviceAction(kClear[f], 0, 0.0f);+ fx_[part][f]->wake();+ fxWasOn_[part][f] = true;+ }+ fx_[part][f]->process(fxBuf_, n);+ }+ float partPk = 0.0f;+ for (int i = 0; i < n; ++i) {+ out[2 * i] += fxBuf_[2 * i];+ out[2 * i + 1] += fxBuf_[2 * i + 1];+ partPk = std::max(partPk, std::max(std::fabs(fxBuf_[2 * i]), std::fabs(fxBuf_[2 * i + 1])));+ }+ pk = std::max(pk, partPk);+ // Upper's tail after a switch to Single: done once no voice of it sounds and it is quiet.+ if (part == 1 && layoutMode() == 0) {+ upperQuiet_ = sounding || partPk > 1.0e-5f ? 0 : upperQuiet_ + static_cast<uint64_t>(n);+ const uint64_t hang = kIdleHangover + (fxWasOn_[1][FxDelay] ? static_cast<uint64_t>(sr_ * kDelayHoldSec) : 0); // echoes rest in silence+ if (upperQuiet_ > hang) upperTail_ = false, upperQuiet_ = 0;+ }+ }+ blockPeak_ = pk;+ activeVoices_.store(active, std::memory_order_relaxed);+}++// Picks up a new device rate; voices keep their notes, only rate-derived state restarts.+void Twin::applyRate() {+ const double sr = sampleRate_.load(std::memory_order_relaxed);+ if (sr == sr_) return;+ sr_ = sr;+ os_ = sr_ >= 88000.0 ? 1 : 2;+ fadeLen_ = std::max(1, static_cast<int>(0.004 * sr_));+ static const double kSteep[12] = {0.017347915108876406, 0.067150480426919179, 0.14330738338179819,+ 0.23745131944299824, 0.34085550201503761, 0.44601111310335906, 0.54753112652956148, 0.6423859124721446,+ 0.72968928615804163, 0.81029959388029904, 0.88644514917318362, 0.96150605146543733};+ for (auto& part : dn_)+ for (auto& d : part) {+ d.set_coefs(kSteep);+ d.clear_buffers();+ }+ ctlInit_ = false;+ ctlLeft_ = 0;+}++void Twin::render(float* out, int32_t frames) {+ SnapshotHistory<twin::PatternSet>::RenderScope patScope(pats_);+ dsp::ScopedNoDenormals ftz;+ applyRate();+ // Asleep — no voice, a quiet hangover, no sequencer that could play — so nothing to add+ // until a note, a pattern edit or a transport start wakes it (SC-006).+ if (wakeReq_.exchange(false, std::memory_order_acquire)) {+ quiet_ = 0;+ idle_.store(false, std::memory_order_relaxed);+ }+ if (idle_.load(std::memory_order_relaxed) && !seqActive()) {+ tFrames_ += frames;+ return;+ }+ for (int32_t done = 0; done < frames;) {+ if (ctlLeft_ == 0) {+ updateControl(clockAt(done));+ ctlLeft_ = twin::kCtl;+ }+ const int toEvent = seqService(done); // fires due steps, says when the next one is+ const int n = std::min<int>({ctlLeft_, frames - done, toEvent});+ renderSegment(out + done * 2, n);+ ctlLeft_ -= n;+ done += n;+ }+ tFrames_ += frames;+ if (!playing_) freeT_ += frames;+ if (activeVoices_.load(std::memory_order_relaxed) == 0 && blockPeak_ <= 1.0e-5f && !seqRunning_) quiet_ += static_cast<uint64_t>(frames);+ else quiet_ = 0;+ // A delay holds its echoes in silence: while one is on, wait out its longest time too.+ bool delayOn = false;+ for (const auto& part : fxWasOn_) delayOn |= part[FxDelay];+ const uint64_t hang = kIdleHangover + (delayOn ? static_cast<uint64_t>(sampleRate_.load(std::memory_order_relaxed) * kDelayHoldSec) : 0);+ idle_.store(quiet_ > hang, std::memory_order_relaxed);+ publishTelemetry(blockPeak_);+ blockPeak_ = 0.0f;+ heldPub_[0].store(heldBits_[0], std::memory_order_relaxed);+ heldPub_[1].store(heldBits_[1], std::memory_order_relaxed);+}++void Twin::publishTelemetry(float peak) {+ auto set = [&](int i, float v) { tele_[i].store(v, std::memory_order_relaxed); };+ set(ScStep, seqRunning_ ? static_cast<float>(playStep_) : -1.0f);+ set(ScPattern, static_cast<float>(curPat_));+ set(ScPending, static_cast<float>(pendPat_));+ set(ScRevision, static_cast<float>(rev_.load(std::memory_order_relaxed)));+ int lo = 0, up = 0;+ const twin::Voice* newest = nullptr;+ for (int v = 0; v < kMaxVoices; ++v) {+ const twin::Voice& V = voices_[v];+ if (V.active) {+ (V.part == 0 ? lo : up)++;+ if (!newest || V.order > newest->order) newest = &V;+ }+ const float base = std::clamp(twin::partMorph(pn_, V.part) + partMorphOff_[V.part], 0.0f, 1.0f);+ set(ScVoiceMorph0 + v, V.active ? std::clamp(base + V.morphOff, 0.0f, 1.0f) : -1.0f);+ }+ set(ScVoicesLo, static_cast<float>(lo));+ set(ScVoicesUp, static_cast<float>(up));+ for (int p = 0; p < twin::kParts; ++p)+ set(ScMorphLo + p, std::clamp(twin::partMorph(pn_, p) + partMorphOff_[p], 0.0f, 1.0f));+ // An LFO's phase: the shared one in global mode, else the newest voice's.+ for (int l = 0; l < 3; ++l) {+ const bool global = ctl_[0].lfoGlobal[l];+ const double ph = global ? glfo_[0][l].ph : newest ? newest->lfo[l].ph : 0.0;+ set(ScLfoPhase0 + l, static_cast<float>(ph));+ }+ set(ScPeakDb, peak > 1e-9f ? 20.0f * std::log10(peak) : -180.0f);+}++int32_t Twin::scopeRead(float* out, int32_t maxN) const {+ const int32_t n = std::min<int32_t>(maxN, kScopeN);+ for (int32_t i = 0; i < n; ++i) out[i] = tele_[i].load(std::memory_order_relaxed);+ return n;+}++int32_t Twin::heldNotes(int32_t* out, int32_t maxN) const {+ int32_t n = 0;+ for (int w = 0; w < 2; ++w) {+ const uint64_t bits = heldPub_[w].load(std::memory_order_relaxed);+ for (int b = 0; b < 64 && n < maxN; ++b)+ if (bits & (uint64_t{1} << b)) out[n++] = w * 64 + b;+ }+ return n;+}++// ---- project state ----------------------------------------------------------------------++std::vector<uint8_t> Twin::getState() const {+ std::vector<uint8_t> b;+ b.reserve(12 + kNumParams * sizeof(float));+ putU32(b, kStateMagic);+ putU32(b, static_cast<uint32_t>(kNumParams));+ for (int i = 0; i < kNumParams; ++i) {+ const float v = pn_[i].load(std::memory_order_relaxed);+ uint32_t u;+ std::memcpy(&u, &v, sizeof u);+ putU32(b, u);+ }+ const auto pat = twin::serializePatterns(*patAuth_);+ putU32(b, static_cast<uint32_t>(pat.size()));+ b.insert(b.end(), pat.begin(), pat.end());+ return b;+}++void Twin::setState(const uint8_t* data, int32_t size) {+ if (!data || size < 8 || getU32(data) != kStateMagic) return;+ const uint32_t count = getU32(data + 4);+ const size_t avail = (static_cast<size_t>(size) - 8) / sizeof(float);+ const int n = static_cast<int>(std::min<size_t>({count, avail, static_cast<size_t>(kNumParams)}));+ for (int i = 0; i < n; ++i) {+ const uint32_t u = getU32(data + 8 + i * sizeof(float));+ float v;+ std::memcpy(&v, &u, sizeof v);+ if (std::isfinite(v)) pn_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed);+ }+ // The pattern block after the params (a preset may carry only it: paramCount 0).+ const size_t at = 8 + static_cast<size_t>(count) * sizeof(float);+ if (static_cast<size_t>(size) >= at + 4) {+ const uint32_t bytes = getU32(data + at);+ if (static_cast<size_t>(size) >= at + 4 + bytes) setEditState(data + at + 4, static_cast<int32_t>(bytes));+ }+}++std::vector<uint8_t> Twin::editState() const {+ return twin::serializePatterns(*patAuth_);+}++void Twin::setEditState(const uint8_t* data, int32_t size) {+ auto next = std::make_shared<twin::PatternSet>();+ if (!twin::deserializePatterns(data, size, *next)) return;+ patAuth_ = next;+ publishPatterns();+}++void Twin::publishPatterns() {+ pats_.publish(std::make_shared<twin::PatternSet>(*patAuth_));+ rev_.fetch_add(1, std::memory_order_relaxed);+ wake();+}++// ---- the sequencer's editing channel (message thread) -------------------------------------+void Twin::action(int32_t id, int32_t iarg, float farg) {+ using namespace twin;+ Pattern& P = editPattern();+ auto stepOk = [&](int st) { return st >= 0 && st < kSteps; };+ bool changed = true;+ switch (id) {+ case A_SelectPattern:+ if (iarg >= 0 && iarg < kPatterns) editPat_ = iarg;+ changed = false;+ break;+ case A_SetLength:+ P.length = static_cast<uint8_t>(std::clamp(iarg, 1, kSteps));+ if (recStep_ >= P.length) recStep_ = 0; // the record cursor stays on the pattern+ break;+ case A_ClearStep:+ if (stepOk(iarg)) P.step[iarg].n = 0;+ break;+ case A_AddStepNote: {+ const int st = iarg >> 8, note = iarg & 0xFF;+ if (!stepOk(st) || note > 127) break;+ Step& S = P.step[st];+ bool has = false;+ for (int i = 0; i < S.n; ++i) has |= S.note[i] == note;+ if (!has && S.n < kStepNotes) S.note[S.n++] = static_cast<uint8_t>(note);+ if (farg > 0.0f) S.vel = static_cast<uint8_t>(std::clamp<int>(static_cast<int>(std::lround(farg * 127.0f)), 1, 127));+ break;+ }+ case A_RemoveStepNote: {+ const int st = iarg >> 8, note = iarg & 0xFF;+ if (!stepOk(st)) break;+ Step& S = P.step[st];+ int w = 0;+ for (int i = 0; i < S.n; ++i)+ if (S.note[i] != note) S.note[w++] = S.note[i];+ S.n = static_cast<uint8_t>(w);+ break;+ }+ case A_SetStepVelocity:+ if (stepOk(iarg)) P.step[iarg].vel = static_cast<uint8_t>(std::clamp<int>(static_cast<int>(std::lround(farg * 127.0f)), 1, 127));+ break;+ case A_SetStepGate:+ if (stepOk(iarg))+ P.step[iarg].gate = farg > 1.0f ? kGateTie : static_cast<uint8_t>(std::clamp<int>(static_cast<int>(std::lround(farg * 100.0f)), 1, 100));+ break;+ case A_StepRecordArm:+ recArmed_.store(iarg != 0, std::memory_order_relaxed);+ recStep_ = 0, recChordN_ = 0, recDown_[0] = recDown_[1] = 0;+ ringTail_.store(ringHead_.load(std::memory_order_acquire), std::memory_order_release);+ changed = false;+ break;+ case A_StepRecordAdvance:+ P.step[recStep_].n = 0;+ recStep_ = (recStep_ + 1) % P.length;+ break;+ case A_ClearPattern:+ if (iarg >= 0 && iarg < kPatterns) patAuth_->pat[iarg] = Pattern{};+ break;+ case A_CopyPattern: {+ const int from = iarg >> 8, to = iarg & 0xFF;+ if (from >= 0 && from < kPatterns && to >= 0 && to < kPatterns && from != to) patAuth_->pat[to] = patAuth_->pat[from];+ break;+ }+ case A_MotionTarget: {+ const int lane = iarg >> 16, param = iarg & 0xFFFF;+ if (lane >= 0 && lane < kLanes) P.lane[lane].target = param == 0xFFFF || param >= kNumParams ? int16_t{-1} : static_cast<int16_t>(param);+ break;+ }+ case A_MotionMode:+ if (iarg >= 0 && iarg < kLanes) P.lane[iarg].smooth = farg >= 0.5f ? 1 : 0;+ break;+ case A_MotionSet: {+ const int lane = iarg >> 8, st = iarg & 0xFF;+ if (lane >= 0 && lane < kLanes && stepOk(st))+ P.lane[lane].val[st] = farg < 0.0f ? kMotionUnset : static_cast<uint16_t>(std::lround(std::clamp(farg, 0.0f, 1.0f) * 65534.0f));+ break;+ }+ case A_MotionRecordArm:+ recLane_.store(iarg >= 0 && iarg < kLanes ? iarg : -1, std::memory_order_relaxed);+ changed = false;+ break;+ case A_ClearMotion:+ if (iarg >= 0 && iarg < kLanes) P.lane[iarg] = Lane{};+ break;+ case A_StepRecordPoll: {+ // A chord is the notes held together; it lands on the record step when the last one lifts.+ changed = false;+ const uint32_t head = ringHead_.load(std::memory_order_acquire);+ uint32_t tail = ringTail_.load(std::memory_order_relaxed);+ for (; tail != head; ++tail) {+ const uint32_t e = ring_[tail % kRing].load(std::memory_order_relaxed);+ const int pitch = static_cast<int>((e >> 8) & 0x7F);+ const uint64_t bit = uint64_t{1} << (pitch & 63);+ if (e & (1u << 16)) {+ recDown_[pitch >> 6] &= ~bit;+ if ((recDown_[0] | recDown_[1]) == 0 && recChordN_ > 0) {+ Step& S = P.step[recStep_];+ S.n = static_cast<uint8_t>(recChordN_);+ std::copy(recChord_, recChord_ + recChordN_, S.note);+ S.vel = static_cast<uint8_t>(std::clamp(recVel_, 1, 127));+ recStep_ = (recStep_ + 1) % P.length;+ recChordN_ = recVel_ = 0;+ changed = true;+ }+ } else {+ recDown_[pitch >> 6] |= bit;+ bool has = false;+ for (int i = 0; i < recChordN_; ++i) has |= recChord_[i] == pitch;+ if (!has && recChordN_ < kStepNotes) recChord_[recChordN_++] = static_cast<uint8_t>(pitch);+ recVel_ = std::max(recVel_, static_cast<int>(e & 0x7F));+ }+ }+ ringTail_.store(tail, std::memory_order_release);+ break;+ }+ default: changed = false; break;+ }+ // The record cursor is message-thread state: published here, not by the render.+ tele_[ScRecStep].store(recArmed_.load(std::memory_order_relaxed) ? static_cast<float>(recStep_) : -1.0f, std::memory_order_relaxed);+ if (changed) publishPatterns();+}++std::shared_ptr<Instrument> Twin::clone() const {+ auto s = std::make_shared<Twin>();+ for (int i = 0; i < kNumParams; ++i)+ s->pn_[i].store(pn_[i].load(std::memory_order_relaxed), std::memory_order_relaxed);+ s->patAuth_ = std::make_shared<twin::PatternSet>(*patAuth_);+ s->publishPatterns();+ s->setSampleRate(sampleRate_.load(std::memory_order_relaxed));+ return s;+}++} // namespace notadiff --git a/src/native/nota.engine/src/devices/instruments/Twin.h b/src/native/nota.engine/src/devices/instruments/Twin.hnew file mode 100644index 00000000..dda951fd--- /dev/null+++ b/src/native/nota.engine/src/devices/instruments/Twin.h@@ -0,0 +1,495 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Twin — the built-in two-part morphing analog poly (kind 18, specs/055). Nota's own DSP.+//+// The patch is up to two parts (Lower / Upper: Single, Layer or Split) sharing 12 voices.+// Every sound parameter of a part exists twice, as an A and a B plugin-param, and the part's+// Morph sweeps between them. Keeping the sides as ordinary params is the design's core: an+// automation lane, a MIDI-learned knob, a macro or a CV link on "Lower A · Ladder Cutoff"+// moves exactly that side, and presets, clone and undo need nothing new (research R2).+//+// Param layout (persisted order — APPEND ONLY, see the tables in Twin.cpp):+// [globals][Lower: part params][Lower A][Lower B][Upper: part params][Upper A][Upper B]+// Matrix sources / destinations are stored as index / kSrcScale and index / kDstScale, so new+// entries fit without re-encoding saved patches. The sequencer's patterns are structural+// state (the state blob), not params.+//+// Files: this one (params, state, the voice pool and render), TwinVoice (one voice's DSP),+// TwinMod (morph and the param → sound mapping); the sequencer (TwinSeq) arrives with US8.+//+// Rendering: control values are refreshed every twin::kCtl samples on a grid counted from the+// last reset, never from block starts, so the same notes render the same whatever the host's+// block size. Voices run at ×2 (×1 from 88.2 kHz); one HIIR half-band decimator per channel+// brings the voice sum down. Deterministic: drift, oscillator start phases and noise come+// from seeded generators, re-seeded on allNotesOff and on a transport start or jump while+// silent, so a freeze equals the live render.++#pragma once++#include "devices/Device.h"+#include "devices/Instrument.h"+#include "devices/instruments/TwinSeq.h"+#include "devices/instruments/TwinVoice.h"+#include "engine/SnapshotHistory.h"++#include <algorithm>+#include <atomic>+#include <cmath>+#include <cstdint>+#include <memory>+#include <string>+#include <vector>++namespace nota {++namespace twin {++// How a continuous value maps to its musical units. The normalized value of a Pitch or LogTime+// param is already exponential in its unit, so interpolating normalized values (the morph)+// moves cutoffs in pitch and times logarithmically.+enum class Domain : uint8_t { Linear, Pitch, LogTime };++constexpr int kParts = 2; // 0 = Lower, 1 = Upper+constexpr int kSides = 2; // 0 = A, 1 = B+constexpr int kRoutes = 64; // matrix slots per part+constexpr int kMacros = 8; // per part+constexpr int kMaxVoices = 12; // shared by the parts+constexpr int kSrcScale = 63; // matrix source index / kSrcScale = the stored value+constexpr int kDstScale = 255; // matrix destination index / kDstScale++// Patch-wide params.+enum Global : int {+ GMode = 0, // Single / Layer / Split+ GSplitKey,+ GShare, // Lower's voices: 2, 4, 6, 8, 10+ GVoices, // 4..12+ GPadX,+ GPadY,+ GPadZ,+ GBendRange, // ±2 / ±5 / ±12 / ±24+ GSeqOn,+ GSeqKind, // Seq / Arp+ GSeqPattern,+ GSeqRate,+ GSeqSwing,+ GSeqLatch,+ GSeqTranspose,+ GSeqTarget, // Lower / Upper / Both+ GArpMode,+ GArpOct,+ GArpGate,+ GArpHold,+ GView, // card size (editor state, not sound)+ kGlobalN+};++// Per part, side-less.+enum PartParam : int {+ PMorph = 0,+ PVoiceMode, // Poly / Mono / Legato / Unison+ PGlide,+ PGlideLegato,+ POctave, // −2..+2 (Split transpose)+ PVol,+ PPan,+ PFxOn, // the whole effects section+ PMacro0,+ PRoute0 = PMacro0 + kMacros, // slot n: PRoute0 + 2n = source, + 2n + 1 = destination+ kPartN = PRoute0 + 2 * kRoutes+};++// Per part per side: the morphed sound.+enum SideParam : int {+ O1Wave = 0,+ O1Pw,+ O1Metal,+ O1Coarse,+ O1Fine,+ O1Level,+ O1Bal, // 0 = multimode, 1 = ladder+ O2Wave,+ O2Pw,+ O2Metal,+ O2Coarse,+ O2Fine,+ O2Level,+ O2Bal,+ Sync,+ Fm21,+ FmFilt,+ O2Lo,+ NoiseLevel,+ NoiseColor,+ NoiseBal,+ MmCut,+ MmRes,+ MmMode,+ MmKey,+ MmEnv,+ LdCut,+ LdRes,+ LdSlope, // 12 / 24 dB+ LdKey,+ LdEnv,+ Route, // 0 = series (multimode → ladder), 1 = parallel+ Brute,+ Drive,+ FEnvA,+ FEnvD,+ FEnvS,+ FEnvR,+ FEnvVel,+ FEnvCurve,+ AEnvA,+ AEnvD,+ AEnvS,+ AEnvR,+ AEnvVel,+ AEnvCurve,+ MEnvDly,+ MEnvA,+ MEnvD,+ MEnvS,+ MEnvR,+ MEnvVel,+ MEnvLoop,+ Lfo1Shape,+ Lfo1Rate,+ Lfo1Sync,+ Lfo1Div,+ Lfo1Mode, // per voice / global+ Lfo1Retrig,+ Lfo1Fade,+ Lfo1Amt,+ Lfo2Shape,+ Lfo2Rate,+ Lfo2Sync,+ Lfo2Div,+ Lfo2Mode,+ Lfo2Retrig,+ Lfo2Fade,+ Lfo2Amt,+ Lfo3Shape,+ Lfo3Rate,+ Lfo3Sync,+ Lfo3Div,+ Lfo3Mode,+ Lfo3Retrig,+ Lfo3Fade,+ Lfo3Amt,+ Lfo3Sym,+ Lfo3Curve,+ VibAmt, // LFO 1 → pitch, scaled by the mod wheel+ Drift,+ UniDetune,+ Spread,+ SpreadMode, // by voice / by key / unison+ ModFxType, // chorus / flanger / phaser / ensemble+ ModFxRate,+ ModFxDepth,+ ModFxMix,+ DlyTime,+ DlySync,+ DlyDiv,+ DlyFb,+ DlyPingPong,+ DlyMix,+ RevSize,+ RevDamp,+ RevMix,+ ModFxOn,+ DlyOn,+ RevOn,+ MatAmt0, // slot n's depth on this side (bipolar, 0.5 = none)+ kSideN = MatAmt0 + kRoutes+};++constexpr int kPartBlock = kPartN + kSides * kSideN;+constexpr int kNumParams = kGlobalN + kParts * kPartBlock;++constexpr int globalIdx(int g) { return g; }+constexpr int partIdx(int part, int p) { return kGlobalN + part * kPartBlock + p; }+constexpr int sideIdx(int part, int side, int s) { return kGlobalN + part * kPartBlock + kPartN + side * kSideN + s; }++struct ParamInfo {+ std::string id; // stable: "mode", "lo.morph", "lo.a.ldcut", "up.b.m12amt"+ std::string name; // display: "Lower A · Ladder Cutoff" (the automation menu groups on the head before the last space)+ float def = 0.0f; // normalized default+ uint16_t steps = 0; // 0 = continuous, else the number of positions (morph switches at the midpoint)+ Domain domain = Domain::Linear;+};++// The whole table, built once on first use (message thread).+const std::vector<ParamInfo>& paramTable();++} // namespace twin++class Twin final : public Instrument {+ public:+ static constexpr int kNumParams = twin::kNumParams;+ static constexpr uint32_t kStateMagic = 0x314E5754; // "TWN1"++ Twin();++ int32_t kind() const override { return 18; }+ const char* displayName() const override { return "Nota Twin"; }++ // The voices pick the rate up at the next render; the effect devices are re-prepared here —+ // the engine changes rates with rendering suspended (Engine::propagateSampleRate), and their+ // delay / reverb lines are sized to the rate.+ void setSampleRate(double sr) override;+ void setTransportInfo(const TransportInfo& ti) override;+ void noteOn(int32_t pitch, float velocity) override;+ void noteOff(int32_t pitch) override;+ void noteOffVelocity(int32_t pitch, float velocity) override;+ void allNotesOff() override;+ void controller(int32_t ctl, float value) override; // CC1 = the mod wheel+ // Per-note expression (MPE, poly aftertouch) and the instrument-wide wheel / pressure / CC74.+ void noteExpression(int32_t pitch, int32_t dim, float value) override;+ bool supportsMpe() const override { return true; }+ void setTransport(double beatStart, double samplesPerBeat, bool playing) override;+ void render(float* out, int32_t frames) override;++ int32_t activeVoiceCount() const override { return activeVoices_.load(std::memory_order_relaxed); }+ // Live view for the card (contracts/c-abi.md § scopeRead, append-only): see the Scope enum.+ enum Scope : int {+ ScStep = 0, // the sequencer (US8): playing step, −1 stopped+ ScPattern, // playing pattern+ ScPending, // pending pattern, −1 none+ ScRevision, // pattern edit revision+ ScVoicesLo, // sounding voices, Lower+ ScVoicesUp, // … Upper+ ScMorphLo, // the part's live morph (knob + patch-wide routes)+ ScMorphUp,+ ScVoiceMorph0, // per voice: its live morph, −1 idle (12 values)+ ScLfoPhase0 = ScVoiceMorph0 + twin::kMaxVoices, // LFO 1–3 phase 0..1 (Lower)+ ScPeakDb = ScLfoPhase0 + 3, // output peak, dBFS+ ScRecStep, // the step the next recorded chord lands on (−1 = not recording)+ ScLastKey, // the last key played (−1 none): the card's split-point learn+ kScopeN+ };+ // The sequencer's editing channel (contracts/c-abi.md, append-only). Each edit is one undo+ // step (editState); they act on the pattern selected for editing (A_SelectPattern).+ enum Act : int32_t {+ A_SelectPattern = 0, // iarg pattern 0..7+ A_SetLength, // iarg steps 1..64+ A_ClearStep, // iarg step+ A_AddStepNote, // iarg step << 8 | note, farg velocity 0..1+ A_RemoveStepNote, // iarg step << 8 | note+ A_SetStepVelocity, // iarg step, farg 0..1+ A_SetStepGate, // iarg step, farg 0..1 (> 1 = tie into the next step)+ A_StepRecordArm, // iarg 1 = arm (from step 1), 0 = off+ A_StepRecordAdvance, // a rest at the record cursor+ A_ClearPattern, // iarg pattern+ A_CopyPattern, // iarg from << 8 | to+ A_MotionTarget, // iarg lane << 16 | param index (0xFFFF = none)+ A_MotionMode, // iarg lane, farg 0 stepped / 1 smooth+ A_MotionSet, // iarg lane << 8 | step, farg 0..1 (< 0 = unset)+ A_MotionRecordArm, // iarg lane (−1 = off): the lane's playback pauses while it records+ A_ClearMotion, // iarg lane+ A_StepRecordPoll, // the card's tick: turns the notes played while armed into steps+ };+ void action(int32_t id, int32_t iarg, float farg) override;+ std::vector<uint8_t> editState() const override;+ void setEditState(const uint8_t* data, int32_t size) override;+ int32_t scopeRead(float* out, int32_t maxN) const override;+ int32_t heldNotes(int32_t* out, int32_t maxN) const override;++ // Sleep contract: the voices are the tail; once none sounds and the output has been+ // quiet for a hangover (the decimator drain), the instrument may sleep. Notes, param+ // edits and transport starts wake it.+ bool hasTail() const override { return true; }+ // wake() may come from the UI thread (a knob, a pattern edit) while render() runs, so it only+ // raises a request; the audio thread owns quiet_ / idle_ and clears them when it takes it.+ bool isIdle() const override {+ return idle_.load(std::memory_order_relaxed) && !wakeReq_.load(std::memory_order_relaxed);+ }+ void wake() override { wakeReq_.store(true, std::memory_order_release); }++ // ---- parameters -----------------------------------------------------------+ int32_t pluginParamCount() const override { return kNumParams; }+ std::string pluginParamId(int32_t i) const override;+ std::string pluginParamName(int32_t i) const override;+ float pluginParamGet(int32_t i) const override {+ return (i >= 0 && i < kNumParams) ? pn_[i].load(std::memory_order_relaxed) : 0.0f;+ }+ void pluginParamSet(int32_t i, float v) override {+ if (i >= 0 && i < kNumParams && std::isfinite(v))+ pn_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed);+ wake();+ }+ std::string pluginParamText(int32_t i) const override;+ float pluginParamDefault(int32_t i) const override;+ int32_t pluginParamIndexOfId(const std::string& id) const override;++ // ---- project state --------------------------------------------------------+ // [u32 "TWN1"][u32 paramCount][paramCount × f32 LE][u32 patternBytes][pattern data].+ // setState takes a shorter / longer param array and a missing pattern block (FR-052).+ std::vector<uint8_t> getState() const override;+ void setState(const uint8_t* data, int32_t size) override;+ std::shared_ptr<Instrument> clone() const override;++ private:+ static constexpr int kMaxVoices = twin::kMaxVoices;+ static constexpr int kMaxHeld = 32;+ static constexpr float kOutGain = 0.353f; // voice sum → output: Init sits with Volt's Init+ static constexpr uint64_t kIdleHangover = 16384; // frames of silence before sleep+ static constexpr double kDelayHoldSec = 2.5; // + this with a delay on (its longest time is 2 s)++ float get(int i) const { return pn_[i].load(std::memory_order_relaxed); }+ int voiceCap() const { return 4 + twin::stepOf(get(twin::GVoices), 9); }+ // Audio thread.+ void applyRate();+ void resetAll();+ void computeStatics(int v);+ void updateControl(double now); // now: the interval's first sample, absolute (song) frames+ float sourceValue(const twin::Voice& V, const twin::PartCtl& c, int src) const;+ float globalValue(int part, const twin::PartCtl& c, int src) const;+ void modulateVoice(twin::Voice& V, float morph, const twin::LiveRoute* routes, int n);+ void partModulation(int part, float morph);+ void pushFx(int part);+ void renderSegment(float* out, int n);+ int allocate(int first, int count, bool& fade);+ void startVoice(int v, int note, float vel, int s, int S, bool glide);+ void startPending(twin::Voice& V);+ void wakeVoice(twin::Voice& V);+ void release(twin::Voice& V);+ void pushHeld(int part, int note);+ void removeHeld(int part, int note);+ // Parts (US9): the layout, each part's share of the voices, which parts a key / the sequencer plays.+ struct Slice {+ int first, count;+ };+ int layoutMode() const; // 0 Single, 1 Layer, 2 Split+ Slice slice(int part) const;+ int keyParts(int pitch, int* out) const;+ int seqParts(int* out) const;+ void keyOnPart(int part, int pitch, float vel);+ void keyOffPart(int part, int pitch);+ // Notes: from the keyboard (keyOn / keyOff, with the held-key stack) or from the sequencer.+ void keyOn(int pitch, float vel);+ void keyOff(int pitch);+ void seqOn(int pitch, float vel);+ void seqOff(int pitch);+ // The sequencer (audio thread): fire what is due at `offset` samples into this render call+ // and return how far the next event is.+ bool seqActive() const;+ int seqService(int offset);+ void fireStep(int64_t k, double onset);+ void releaseSeqNotes();+ double stepBeats() const;+ double onsetSample(int64_t k) const;+ // Patterns (message thread).+ void publishPatterns();+ twin::Pattern& editPattern() { return patAuth_->pat[editPat_]; }++ std::atomic<float> pn_[kNumParams];+ std::atomic<double> sampleRate_{44100.0};+ std::atomic<int32_t> activeVoices_{0};+ std::atomic<uint64_t> heldPub_[2] = {0, 0};+ std::atomic<float> tele_[kScopeN] = {};+ void publishTelemetry(float peak);++ // ---- audio-thread state ----+ twin::Voice voices_[kMaxVoices];+ twin::PartCtl ctl_[twin::kParts];+ twin::Lfo glfo_[twin::kParts][3]; // LFOs in global mode, per part+ twin::LiveRoute routes_[twin::kParts][twin::kRoutes];+ int routeN_[twin::kParts] = {0, 0};+ float modOff_[twin::kSideN] = {}; // scratch: one voice's side offsets+ // What the routes from patch-wide sources (wheels, pad, macros, global LFOs) do to a whole+ // part this interval; the part's own PartCtl already includes it, and so do its voices.+ float partOff_[twin::kParts][twin::kSideN] = {};+ float partMorphOff_[twin::kParts] = {}, partPitch_[twin::kParts][2] = {}, partVib_[twin::kParts] = {};+ bool partHasOff_[twin::kParts] = {};+ float gLfo1_[twin::kParts][twin::kCtl] = {};+ float morphNow_[twin::kParts] = {}; // each part's morph this interval (knob or motion lane)+ double sr_ = 0.0;+ int os_ = 2;+ int fadeLen_ = 176;+ int ctlLeft_ = 0; // samples until the next control refresh+ bool ctlInit_ = false;+ int lastMode_[twin::kParts] = {-1, -1}, lastCap_ = -1, lastLayout_ = -1;+ uint64_t orderCtr_ = 0;+ int held_[twin::kParts][kMaxHeld] = {};+ int heldN_[twin::kParts] = {};+ uint64_t heldBits_[2] = {0, 0};+ float modWheel_ = 0.0f;+ GlobalExpr gexpr_;+ // transport+ double spb_ = 0.0, beat_ = 0.0, tPos_ = 0.0, tFrames_ = 0.0;+ bool playing_ = false;+ // Transport stopped, the sequencer on: a held key runs it on its own clock at the host tempo+ // (Seq from its first step, transposed by the key; Arp over the held keys). freeT_ counts+ // samples from the key that started it.+ bool freeRun_ = false;+ twin::PartCtl fxHold_[twin::kParts]; // the note that last set a part's effects (per-note routes)+ bool fxHeld_[twin::kParts] = {false, false};+ float gLfoFade_[twin::kParts][3] = {{1, 1, 1}, {1, 1, 1}}; // the global LFOs' fade-in, from a phrase's first key+ bool upperTail_ = false; // Upper still releasing after a switch to Single+ uint64_t upperQuiet_ = 0;+ double freeT_ = 0.0;+ double clockAt(int offset) const { return (playing_ ? tPos_ + tFrames_ : freeT_) + offset; }+ bool seqLatched() const;+ void freeStart();+ void freeStop();+ // decimation, per part+ hiir::Downsampler2xFpu<12> dn_[twin::kParts][2];+ float osL_[twin::kCtl * twin::kMaxOs] = {}, osR_[twin::kCtl * twin::kMaxOs] = {};+ float dsL_[twin::kCtl] = {}, dsR_[twin::kCtl] = {};+ // effects, per part: Chorus, Flanger, Phaser, Delay, Reverb — built once, allocation-free after+ enum Fx { FxChorus = 0, FxFlanger, FxPhaser, FxDelay, FxReverb, kFxN };+ std::unique_ptr<Device> fx_[twin::kParts][kFxN];+ bool fxWasOn_[twin::kParts][kFxN] = {};+ float fxBuf_[twin::kCtl * 2] = {};+ // ---- the sequencer ----+ // message thread: the authoring copy, what the edits address, step record+ std::shared_ptr<twin::PatternSet> patAuth_;+ int editPat_ = 0, recStep_ = 0;+ uint8_t recChord_[twin::kStepNotes] = {};+ int recChordN_ = 0, recVel_ = 0;+ uint64_t recDown_[2] = {0, 0};+ std::atomic<bool> recArmed_{false};+ std::atomic<int> recLane_{-1};+ std::atomic<uint32_t> rev_{0};+ // audio → message: notes played while recording (pitch << 8 | velocity, bit 16 = note-off)+ static constexpr uint32_t kRing = 256;+ std::atomic<uint32_t> ring_[kRing] = {};+ std::atomic<uint32_t> ringHead_{0}, ringTail_{0};+ // audio thread+ SnapshotHistory<twin::PatternSet> pats_;+ bool seqResync_ = true, seqRunning_ = false;+ double seqStepBeats_ = 0.25;+ int64_t nextK_ = 0, arpStartK_ = 0;+ int64_t patStartK_ = 0; // the step index the playing pattern's first step fell on+ float seqStepV_ = 0.0f; // the Seq step source: the playing step, 0 (first) … 1 (last)+ int curPat_ = 0, pendPat_ = -1, playStep_ = -1;+ struct SeqNote {+ int pitch;+ double off; // absolute sample of its note-off (a tie: until the next step decides)+ bool tie;+ };+ SeqNote seqNotes_[32] = {};+ int seqNoteN_ = 0;+ int transpose_ = 0, transKeys_ = 0;+ uint64_t arpTook_[2] = {0, 0}, transTook_[2] = {0, 0}; // the keys the arpeggiator / transpose took, one bit per pitch+ int arpList_[32] = {};+ int arpN_ = 0, arpKeys_ = 0;+ float arpVel_ = 0.8f;+ struct Motion {+ int target = -1; // param index+ float from = 0.0f, to = 0.0f;+ double t0 = 0.0, len = 1.0; // the step's start and length, absolute samples+ bool smooth = false, set = false;+ };+ Motion motion_[twin::kLanes];+ twin::MotionOverride motionOvr_[twin::kParts];+ // sleep+ std::atomic<bool> idle_{false}; // written by render() only+ std::atomic<bool> wakeReq_{false}; // wake(): any thread; taken by render()+ uint64_t quiet_ = 0; // audio thread only+ float blockPeak_ = 0.0f;+};++} // namespace notadiff --git a/src/native/nota.engine/src/devices/instruments/TwinMod.cpp b/src/native/nota.engine/src/devices/instruments/TwinMod.cppnew file mode 100644index 00000000..f1d225fa--- /dev/null+++ b/src/native/nota.engine/src/devices/instruments/TwinMod.cpp@@ -0,0 +1,202 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Twin — morph evaluation and the param → PartCtl mapping (see TwinMod.h).++#include "devices/instruments/TwinMod.h"++#include <algorithm>+#include <cmath>+#include <string>++namespace nota {+namespace twin {++namespace {++// Which side params are stepped (they switch at the morph midpoint), from the param table.+struct SteppedTable {+ bool stepped[kSideN];+ SteppedTable() {+ const auto& t = paramTable();+ for (int s = 0; s < kSideN; ++s) stepped[s] = t[static_cast<size_t>(sideIdx(0, 0, s))].steps > 1;+ }+};+const SteppedTable& steppedTable() {+ static const SteppedTable t;+ return t;+}++} // namespace++float partMorph(const std::atomic<float>* pn, int part) {+ return pn[partIdx(part, PMorph)].load(std::memory_order_relaxed);+}++namespace {++const char* const kSrcNames[kSrcN] = {"None", "LFO 1", "LFO 2", "LFO 3", "Filter env", "Amp env", "Mod env",+ "Velocity", "Release velocity", "Key", "Pressure", "Slide", "Bend", "Mod wheel", "Pitch wheel", "Pad X",+ "Pad Y", "Pad Z", "Random", "Macro 1", "Macro 2", "Macro 3", "Macro 4", "Macro 5", "Macro 6", "Macro 7",+ "Macro 8", "Seq gate", "Seq step"};++// The continuous side params a route may reach, in persisted order — APPEND ONLY.+constexpr int kSideDsts[] = {O1Wave, O1Pw, O1Metal, O1Fine, O1Level, O1Bal, O2Wave, O2Pw, O2Metal, O2Fine, O2Level,+ O2Bal, Fm21, FmFilt, NoiseLevel, NoiseColor, NoiseBal, MmCut, MmRes, MmMode, MmKey, MmEnv, LdCut, LdRes, LdKey, LdEnv,+ Route, Brute, Drive, FEnvA, FEnvD, FEnvS, FEnvR, FEnvVel, FEnvCurve, AEnvA, AEnvD, AEnvS, AEnvR, AEnvVel,+ AEnvCurve, MEnvDly, MEnvA, MEnvD, MEnvS, MEnvR, MEnvVel, Lfo1Rate, Lfo1Fade, Lfo1Amt, Lfo2Rate, Lfo2Fade, Lfo2Amt,+ Lfo3Rate, Lfo3Fade, Lfo3Amt, Lfo3Sym, Lfo3Curve, VibAmt, Drift, UniDetune, Spread, ModFxRate, ModFxDepth,+ ModFxMix, DlyTime, DlyFb, DlyMix, RevSize, RevDamp, RevMix};+constexpr int kVirtualDsts = 6; // None, Morph, Pitch, Osc 1 pitch, Osc 2 pitch, Vibrato+constexpr int kSideDstN = sizeof(kSideDsts) / sizeof(kSideDsts[0]);+static_assert(kVirtualDsts + kSideDstN <= kDstScale + 1, "destinations outgrew their encoding");++} // namespace++const char* srcName(int s) { return s >= 0 && s < kSrcN ? kSrcNames[s] : ""; }++int dstCount() { return kVirtualDsts + kSideDstN; }++Dst dstAt(int i) {+ switch (i) {+ case 1: return {DstMorph, -1};+ case 2: return {DstPitch, -1};+ case 3: return {DstPitch1, -1};+ case 4: return {DstPitch2, -1};+ case 5: return {DstVibrato, -1};+ default:+ if (i >= kVirtualDsts && i < dstCount()) return {DstSide, kSideDsts[i - kVirtualDsts]};+ return {DstNone, -1};+ }+}++const char* dstName(int i) {+ static const char* const kVirtual[kVirtualDsts] = {"None", "Morph", "Pitch", "Osc 1 pitch", "Osc 2 pitch", "Vibrato"};+ if (i >= 0 && i < kVirtualDsts) return kVirtual[i];+ if (i >= dstCount()) return "";+ // The side param's display name after the "Lower A · " prefix: "Ladder Cutoff".+ const std::string& n = paramTable()[static_cast<size_t>(sideIdx(0, 0, kSideDsts[i - kVirtualDsts]))].name;+ const size_t dot = n.find(" · ");+ return dot == std::string::npos ? n.c_str() : n.c_str() + dot + 4;+}++int dstIndexOfSide(int side) {+ for (int i = 0; i < kSideDstN; ++i)+ if (kSideDsts[i] == side) return kVirtualDsts + i;+ return 0;+}++int liveRoutes(const std::atomic<float>* pn, int part, LiveRoute* out) {+ int n = 0;+ for (int r = 0; r < kRoutes; ++r) {+ const int src = stepOf(pn[partIdx(part, PRoute0 + 2 * r)].load(std::memory_order_relaxed), kSrcScale + 1);+ const int dst = stepOf(pn[partIdx(part, PRoute0 + 2 * r + 1)].load(std::memory_order_relaxed), kDstScale + 1);+ if (src <= SrcNone || src >= kSrcN || dst <= 0 || dst >= dstCount()) continue;+ const float a = (pn[sideIdx(part, 0, MatAmt0 + r)].load(std::memory_order_relaxed) - 0.5f) * 2.0f;+ const float b = (pn[sideIdx(part, 1, MatAmt0 + r)].load(std::memory_order_relaxed) - 0.5f) * 2.0f;+ if (a == 0.0f && b == 0.0f) continue; // a route set on one side only still lives on the other+ out[n++] = {src, dst, a, b};+ }+ return n;+}++void evalPart(const std::atomic<float>* pn, int part, float morph, double spb, double sr, PartCtl& c, const float* off,+ const MotionOverride* ovr) {+ const auto& st = steppedTable();+ const int a0 = sideIdx(part, 0, 0), b0 = sideIdx(part, 1, 0);+ // A motion lane sets a side's value outright, before the morph blends the sides.+ auto side = [&](int sd, int s) {+ if (ovr)+ for (int i = 0; i < ovr->n; ++i)+ if (ovr->param[i] == s && ovr->side[i] == sd) return ovr->v[i];+ return pn[(sd == 0 ? a0 : b0) + s].load(std::memory_order_relaxed);+ };+ auto S = [&](int s) {+ const float a = side(0, s);+ float v;+ if (morph <= 0.0f) v = a;+ else {+ const float b = side(1, s);+ v = morph >= 1.0f ? b : st.stepped[s] ? (morph < 0.5f ? a : b) : a + (b - a) * morph;+ }+ return off && off[s] != 0.0f ? std::clamp(v + off[s], 0.0f, 1.0f) : v;+ };+ auto P = [&](int p) { return pn[partIdx(part, p)].load(std::memory_order_relaxed); };++ for (int k = 0; k < 2; ++k) {+ const int o = k * (O2Wave - O1Wave);+ c.semi[k] = static_cast<float>(coarseSemis(S(O1Coarse + o))) + fineSemis(S(O1Fine + o));+ c.wave[k] = S(O1Wave + o);+ c.duty[k] = dutyOf(S(O1Pw + o));+ c.metal[k] = S(O1Metal + o);+ c.lvl[k] = S(O1Level + o);+ c.bal[k] = S(O1Bal + o);+ }+ c.sync = S(Sync) >= 0.5f;+ c.o2lo = S(O2Lo) >= 0.5f;+ c.fm21 = 4.0f * S(Fm21) * S(Fm21);+ c.fmFilt = 6.0f * S(FmFilt) * S(FmFilt);+ c.noiseLvl = S(NoiseLevel);+ c.noiseCol = S(NoiseColor);+ c.noiseBal = S(NoiseBal);++ c.mmCut = cutoffOct(S(MmCut));+ c.mmRes = S(MmRes);+ c.mmMode = S(MmMode);+ c.mmKey = S(MmKey);+ c.mmEnv = envAmtOct(S(MmEnv));+ c.ldCut = cutoffOct(S(LdCut));+ c.ldRes = S(LdRes);+ c.ld12 = S(LdSlope) < 0.5f;+ c.ldKey = S(LdKey);+ c.ldEnv = envAmtOct(S(LdEnv));+ c.route = S(Route);+ c.brute = S(Brute);+ c.drive = S(Drive);++ c.fA = attackSec(S(FEnvA)), c.fD = decaySec(S(FEnvD)), c.fS = S(FEnvS), c.fR = decaySec(S(FEnvR));+ c.fVel = S(FEnvVel), c.fCurve = S(FEnvCurve);+ c.aA = attackSec(S(AEnvA)), c.aD = decaySec(S(AEnvD)), c.aS = S(AEnvS), c.aR = decaySec(S(AEnvR));+ c.aVel = S(AEnvVel), c.aCurve = S(AEnvCurve);+ c.mDly = delaySec(S(MEnvDly));+ c.mA = attackSec(S(MEnvA)), c.mD = decaySec(S(MEnvD)), c.mS = S(MEnvS), c.mR = decaySec(S(MEnvR));+ c.mVel = S(MEnvVel);+ c.mLoop = S(MEnvLoop) >= 0.5f;++ for (int l = 0; l < 3; ++l) {+ const int o = l * (Lfo2Shape - Lfo1Shape);+ c.lfoShape[l] = stepOf(S(Lfo1Shape + o), 6);+ const bool sync = S(Lfo1Sync + o) >= 0.5f && spb > 1.0;+ c.lfoHz[l] = sync ? static_cast<float>(sr / (spb * syncBeats(S(Lfo1Div + o)))) : lfoHz(S(Lfo1Rate + o));+ c.lfoGlobal[l] = S(Lfo1Mode + o) >= 0.5f;+ c.lfoRetrig[l] = S(Lfo1Retrig + o) >= 0.5f;+ c.lfoFade[l] = fadeSec(S(Lfo1Fade + o));+ c.lfoAmt[l] = S(Lfo1Amt + o);+ }+ // LFO 3's shaping, as the card draws it: the triangle's peak, and a curve of 1/4 … 4.+ c.lfoSym[2] = std::clamp(S(Lfo3Sym), 0.02f, 0.98f);+ c.lfoCurve[2] = std::exp2((S(Lfo3Curve) - 0.5f) * 4.0f);+ c.vibSemis = S(VibAmt);+ c.drift = S(Drift);+ c.uniDetune = S(UniDetune);+ c.spread = S(Spread);+ c.spreadMode = stepOf(S(SpreadMode), 3);++ c.fxOn = P(PFxOn) >= 0.5f;+ c.modOn = S(ModFxOn) >= 0.5f, c.dlyOn = S(DlyOn) >= 0.5f, c.revOn = S(RevOn) >= 0.5f;+ c.modType = stepOf(S(ModFxType), 4);+ c.modRate = S(ModFxRate), c.modDepth = S(ModFxDepth), c.modMix = S(ModFxMix);+ c.dlyTime = S(DlyTime), c.dlyDiv = S(DlyDiv), c.dlyFb = S(DlyFb), c.dlyMix = S(DlyMix);+ c.dlySync = S(DlySync) >= 0.5f, c.dlyPing = S(DlyPingPong) >= 0.5f;+ c.revSize = S(RevSize), c.revDamp = S(RevDamp), c.revMix = S(RevMix);++ c.voiceMode = stepOf(P(PVoiceMode), 4);+ c.glideSec = glideSec(P(PGlide));+ c.glideLegato = P(PGlideLegato) >= 0.5f;+ c.octave = stepOf(P(POctave), 5) - 2;+ c.gain = partGain(P(PVol));+ c.pan = (P(PPan) - 0.5f) * 2.0f;+}++} // namespace twin+} // namespace notadiff --git a/src/native/nota.engine/src/devices/instruments/TwinMod.h b/src/native/nota.engine/src/devices/instruments/TwinMod.hnew file mode 100644index 00000000..330a6f1e--- /dev/null+++ b/src/native/nota.engine/src/devices/instruments/TwinMod.h@@ -0,0 +1,75 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Twin — from params to sound: the A↔B morph and the mapping of a part's morphed values+// to the PartCtl its voices read (specs/055 R3). The matrix (US4) joins here.+//+// Morph rule: a continuous param sounds A + (B − A) · morph on its normalized value — the+// exponential params (cutoffs, times, rates) are exponential in that value, so they move in+// pitch / log-time; a stepped param takes A below 0.5 and B from 0.5. Morph 0 and 1 are+// exactly A and B.++#pragma once++#include "devices/instruments/Twin.h"+#include "devices/instruments/TwinVoice.h"++#include <atomic>++namespace nota {+namespace twin {++// ---- the modulation matrix (US4) ---------------------------------------------------------+// A slot is (source, destination, depth on A, depth on B); the depth morphs with the part.+// Both tables are persisted as indices (source / kSrcScale, destination / kDstScale) —+// APPEND ONLY. The card and MCP mirror them (Nota.Application/Twin/TwinMatrix.cs).+enum Src : int {+ SrcNone = 0,+ SrcLfo1,+ SrcLfo2,+ SrcLfo3,+ SrcFiltEnv,+ SrcAmpEnv,+ SrcModEnv,+ SrcVelocity,+ SrcRelVelocity, // the note-off's velocity, 0 while the key is down (FR-030)+ SrcKey, // −1 (C−1) … +1 (C9), 0 at middle C+ SrcPressure,+ SrcSlide,+ SrcBend, // per-note bend, ±24 st → ±1+ SrcModWheel,+ SrcPitchWheel,+ SrcPadX,+ SrcPadY,+ SrcPadZ,+ SrcRandom, // one value per note, −1..1+ SrcMacro1,+ SrcSeqGate = SrcMacro1 + kMacros, // the sequencer (US8)+ SrcSeqStep,+ kSrcN+};+const char* srcName(int s);++// Destination kinds: the morph, pitches and vibrato are virtual; the rest are side params.+enum DstKind : uint8_t { DstNone, DstMorph, DstPitch, DstPitch1, DstPitch2, DstVibrato, DstSide };+struct Dst {+ DstKind kind;+ int side; // SideParam for DstSide+};+int dstCount();+Dst dstAt(int index);+const char* dstName(int index); // "Ladder Cutoff", "Morph", "Pitch"…+int dstIndexOfSide(int side); // the destination index of a side param, or 0+constexpr int kDstMorph = 1, kDstPitch = 2, kDstVibrato = 5;++// The part's routes with a source, a destination and a depth on either side (≤ kRoutes).+int liveRoutes(const std::atomic<float>* pn, int part, LiveRoute* out);++// The part's morph position, then its sounding PartCtl. spb: samples per beat (0 = no tempo),+// for the synced LFO rates. off: normalized offsets per side param (the matrix), or null.+float partMorph(const std::atomic<float>* pn, int part);+void evalPart(const std::atomic<float>* pn, int part, float morph, double spb, double sr, PartCtl& out,+ const float* off = nullptr, const MotionOverride* ovr = nullptr);++} // namespace twin+} // namespace notadiff --git a/src/native/nota.engine/src/devices/instruments/TwinSeq.cpp b/src/native/nota.engine/src/devices/instruments/TwinSeq.cppnew file mode 100644index 00000000..327c08fd--- /dev/null+++ b/src/native/nota.engine/src/devices/instruments/TwinSeq.cpp@@ -0,0 +1,135 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Twin — pattern serialization and the arpeggiator's note order (see TwinSeq.h).++#include "devices/instruments/TwinSeq.h"++#include <algorithm>+#include <cstring>++namespace nota {+namespace twin {++namespace {++constexpr uint32_t kMagic = 0x31505754; // "TWP1"++void put8(std::vector<uint8_t>& b, uint8_t v) { b.push_back(v); }+void put16(std::vector<uint8_t>& b, uint16_t v) {+ b.push_back(static_cast<uint8_t>(v));+ b.push_back(static_cast<uint8_t>(v >> 8));+}+void put32(std::vector<uint8_t>& b, uint32_t v) {+ for (int i = 0; i < 4; ++i) b.push_back(static_cast<uint8_t>(v >> (8 * i)));+}++struct Reader {+ const uint8_t* p;+ int32_t left;+ bool ok = true;+ uint8_t u8() {+ if (left < 1) return ok = false, 0;+ --left;+ return *p++;+ }+ uint16_t u16() {+ const uint16_t lo = u8(), hi = u8();+ return static_cast<uint16_t>(lo | (hi << 8));+ }+ uint32_t u32() {+ uint32_t v = 0;+ for (int i = 0; i < 4; ++i) v |= static_cast<uint32_t>(u8()) << (8 * i);+ return v;+ }+};++uint32_t hash(uint32_t x) {+ x ^= x >> 16;+ x *= 0x7feb352dU;+ x ^= x >> 15;+ x *= 0x846ca68bU;+ x ^= x >> 16;+ return x;+}++} // namespace++std::vector<uint8_t> serializePatterns(const PatternSet& ps) {+ std::vector<uint8_t> b;+ b.reserve(4 + kPatterns * (1 + kSteps * 9 + kLanes * (3 + 2 * kSteps)));+ put32(b, kMagic);+ for (const Pattern& p : ps.pat) {+ put8(b, p.length);+ for (const Step& s : p.step) {+ put8(b, s.n);+ for (uint8_t n : s.note) put8(b, n);+ put8(b, s.vel);+ put8(b, s.gate);+ }+ for (const Lane& l : p.lane) {+ put16(b, static_cast<uint16_t>(l.target));+ put8(b, l.smooth);+ for (uint16_t v : l.val) put16(b, v);+ }+ }+ return b;+}++bool deserializePatterns(const uint8_t* data, int32_t size, PatternSet& out) {+ Reader r{data, size};+ if (!data || r.u32() != kMagic) return false;+ PatternSet ps;+ for (Pattern& p : ps.pat) {+ p.length = static_cast<uint8_t>(std::clamp<int>(r.u8(), 1, kSteps));+ for (Step& s : p.step) {+ s.n = static_cast<uint8_t>(std::min<int>(r.u8(), kStepNotes));+ for (uint8_t& n : s.note) n = static_cast<uint8_t>(std::min<int>(r.u8(), 127));+ s.vel = static_cast<uint8_t>(std::clamp<int>(r.u8(), 1, 127));+ s.gate = static_cast<uint8_t>(std::clamp<int>(r.u8(), 1, kGateTie));+ }+ for (Lane& l : p.lane) {+ l.target = static_cast<int16_t>(r.u16());+ l.smooth = r.u8() ? 1 : 0;+ for (uint16_t& v : l.val) v = r.u16();+ }+ }+ if (!r.ok) return false;+ out = ps;+ return true;+}++int arpNotes(const int* held, int n, int mode, int octaves, int64_t k, uint32_t seed, int* out, int maxN) {+ if (n <= 0 || maxN <= 0) return 0;+ octaves = std::clamp(octaves, 1, 4);+ // The run: the held notes in the mode's order, repeated an octave up per octave.+ int sorted[32];+ const int m = std::min(n, 32);+ std::memcpy(sorted, held, sizeof(int) * static_cast<size_t>(m));+ if (mode != ArpAsPlayed) std::sort(sorted, sorted + m);+ if (mode == ArpChord) {+ const int oct = static_cast<int>(((k % octaves) + octaves) % octaves);+ const int c = std::min(m, maxN);+ for (int i = 0; i < c; ++i) out[i] = std::min(127, sorted[i] + 12 * oct);+ return c;+ }+ const int len = m * octaves;+ auto at = [&](int i) { return std::min(127, sorted[i % m] + 12 * (i / m)); };+ int idx;+ switch (mode) {+ case ArpDown: idx = len - 1 - static_cast<int>(((k % len) + len) % len); break;+ case ArpUpDown: {+ const int cyc = len > 1 ? 2 * len - 2 : 1;+ const int pos = static_cast<int>(((k % cyc) + cyc) % cyc);+ idx = pos < len ? pos : cyc - pos;+ break;+ }+ case ArpRandom: idx = static_cast<int>(hash(seed ^ static_cast<uint32_t>(k) * 0x9E3779B9U) % static_cast<uint32_t>(len)); break;+ default: idx = static_cast<int>(((k % len) + len) % len); break; // Up, As played+ }+ out[0] = at(idx);+ return 1;+}++} // namespace twin+} // namespace notadiff --git a/src/native/nota.engine/src/devices/instruments/TwinSeq.h b/src/native/nota.engine/src/devices/instruments/TwinSeq.hnew file mode 100644index 00000000..9bf2e9a0--- /dev/null+++ b/src/native/nota.engine/src/devices/instruments/TwinSeq.h@@ -0,0 +1,63 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Twin — the sequencer's data (specs/055 US8): eight patterns of up to 64 steps, each step+// up to six notes with a velocity and a gate (or a tie into the next step), and four motion lanes+// per pattern that set a parameter step by step. The patterns are structural state, not params:+// the message thread edits an authoring copy and publishes an immutable snapshot the audio thread+// reads (AR-5); undo swaps the serialized bytes (Instrument::editState).+//+// The arpeggiator's note for a step is a pure function of the step's absolute index (the Nota+// Arp idea), so seeks, loops and block sizes never change what plays.++#pragma once++#include <cstdint>+#include <vector>++namespace nota {+namespace twin {++constexpr int kPatterns = 8, kSteps = 64, kStepNotes = 6, kLanes = 4;+constexpr uint8_t kGateTie = 101; // a step's gate past 100 % holds into the next step+constexpr uint16_t kMotionUnset = 0xFFFF; // a motion lane step that leaves the param alone++struct Step {+ uint8_t n = 0; // notes in the step (0 = rest)+ uint8_t note[kStepNotes] = {};+ uint8_t vel = 100; // 1..127+ uint8_t gate = 50; // 1..100 % of the step, or kGateTie+};++struct Lane {+ int16_t target = -1; // a plugin-param index of the Twin, −1 = none+ uint8_t smooth = 0; // 0 = a step per step, 1 = glide to the next step's value+ uint16_t val[kSteps];+ Lane() {+ for (auto& v : val) v = kMotionUnset;+ }+};++struct Pattern {+ uint8_t length = 16; // 1..64+ Step step[kSteps];+ Lane lane[kLanes];+};++struct PatternSet {+ Pattern pat[kPatterns];+};++// The pattern block of the state blob: [u32 "TWP1"] then per pattern its length, every step+// (n, six notes, velocity, gate) and every lane (target i16, smooth, 64 × u16) — little-endian.+std::vector<uint8_t> serializePatterns(const PatternSet& ps);+bool deserializePatterns(const uint8_t* data, int32_t size, PatternSet& out);++// The arpeggiator (FR-064). Modes: Up, Down, Up/Down, Random, As played, Chord.+enum ArpMode : int { ArpUp = 0, ArpDown, ArpUpDown, ArpRandom, ArpAsPlayed, ArpChord, kArpModes };+// The notes step k plays from `held` (in the order played), over `octaves` octaves: one note,+// or every note for Chord. Writes up to maxN into out and returns the count.+int arpNotes(const int* held, int n, int mode, int octaves, int64_t k, uint32_t seed, int* out, int maxN);++} // namespace twin+} // namespace notadiff --git a/src/native/nota.engine/src/devices/instruments/TwinVoice.cpp b/src/native/nota.engine/src/devices/instruments/TwinVoice.cppnew file mode 100644index 00000000..2110c479--- /dev/null+++ b/src/native/nota.engine/src/devices/instruments/TwinVoice.cpp@@ -0,0 +1,261 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Twin — the voice's per-sample path (see TwinVoice.h).++#include "devices/instruments/TwinVoice.h"++#include <algorithm>+#include <cmath>++namespace nota {+namespace twin {++namespace {++inline float triAt(float p) { return p < 0.5f ? 4.0f * p - 1.0f : 3.0f - 4.0f * p; }++// The triangle's slope corners crossed while the phase moved p0 → p1 (no reset), as BLAMPs.+inline void triCorners(pentad::Osc& o, double p0, float p1, float wrapD, double dt, float gTri) {+ if (gTri == 0.0f) return;+ const float sl = 8.0f * static_cast<float>(dt) * gTri;+ const float inv = static_cast<float>(1.0 / dt);+ if (wrapD >= 0.0f) {+ if (p0 < 0.5) o.ring.blamp((0.5f + p1) * inv, -sl);+ o.ring.blamp(wrapD, sl);+ if (p1 >= 0.5f) o.ring.blamp((p1 - 0.5f) * inv, -sl);+ } else if (p0 < 0.5 && p1 >= 0.5f)+ o.ring.blamp((p1 - 0.5f) * inv, -sl);+}++// One os-rate sample of a triangle / saw / pulse oscillator. syncD ≥ 0: the master wrapped+// syncD samples ago, so this one resets there. Returns this oscillator's own wrap distance+// (−1 = none) and writes its sample to `out`.+inline float oscStep(pentad::Osc& o, double dt, float duty, const WaveGains& w, float syncD, float& out) {+ using namespace pentad;+ const float gz = w.pul * pulseZone(duty);+ float wrap = -1.0f;+ if (syncD >= 0.0f) {+ const double p0 = o.ph;+ advance(o, dt * (1.0 - syncD), syncD, dt, duty, w.saw, gz);+ const float pr = static_cast<float>(o.ph);+ if (w.tri != 0.0f && p0 < 0.5 && pr >= 0.5f) // corner before the reset+ o.ring.blamp(syncD + (pr - 0.5f) * static_cast<float>(1.0 / dt), -8.0f * static_cast<float>(dt) * w.tri);+ o.ring.blep(syncD, -2.0f * pr * w.saw); // saw snaps back to −1+ if (!o.hi && duty > 0.0f) o.ring.blep(syncD, 2.0f * gz);+ o.hi = duty > 0.0f;+ if (w.tri != 0.0f) { // triangle: value jump to −1 and slope back to rising+ o.ring.blep(syncD, (-1.0f - triAt(pr)) * w.tri);+ if (pr >= 0.5f) o.ring.blamp(syncD, 8.0f * static_cast<float>(dt) * w.tri);+ }+ o.ph = 0.0;+ advance(o, dt * syncD, 0.0f, dt, duty, w.saw, gz);+ triCorners(o, 0.0, static_cast<float>(o.ph), -1.0f, dt, w.tri);+ } else {+ const double p0 = o.ph;+ wrap = advance(o, dt, 0.0f, dt, duty, w.saw, gz);+ triCorners(o, p0, static_cast<float>(o.ph), wrap, dt, w.tri);+ }+ const float p = static_cast<float>(o.ph);+ o.ring.naive(w.saw * (2.0f * p - 1.0f) + w.tri * triAt(p) + gz * ((o.hi ? 1.0f : -1.0f) - (2.0f * duty - 1.0f)));+ out = o.ring.pop();+ return wrap;+}++// Metal: a sine folder on the oscillator, first-order antiderivative anti-aliasing.+inline float fold(float x, float drive, double& x1, float& f1) {+ const float a = 1.5707963f * drive;+ const float F = (1.0f - std::cos(a * x)) / a;+ const double dx = x - x1;+ const float y = std::fabs(dx) > 1e-5 ? static_cast<float>((F - f1) / dx) : std::sin(a * 0.5f * (x + static_cast<float>(x1)));+ x1 = x;+ f1 = F;+ return y;+}++inline float softBound(float x) { return x / (1.0f + std::fabs(x)); }++} // namespace++void voiceControl(Voice& V, const PartCtl& c, double sr) {+ // The slow drift walk moves once per control interval.+ V.walkLeft -= kCtl;+ if (V.walkLeft <= 0) {+ V.walkTgt = V.rng.bi();+ V.walkLeft = static_cast<int>(sr * (0.4 + 1.6 * V.rng.uni()));+ }+ V.walk += (V.walkTgt - V.walk) * 0.02f;++ const float ef = 1.0f + c.drift * 0.2f * V.oEnv;+ V.fenv.setTimes(c.fA * ef, c.fD * ef, c.fS, c.fR * ef, c.fCurve, sr, false);+ V.aenv.setTimes(c.aA * ef, c.aD * ef, c.aS, c.aR * ef, c.aCurve, sr, false);+ V.menv.setTimes(c.mA, c.mD, c.mS, c.mR, 0.5f, sr, c.mLoop);+ V.glideC = c.glideSec > 0.0f ? static_cast<float>(1.0 - std::exp(-4.6 / (c.glideSec * sr))) : 1.0f;+ V.mm.setReso(c.mmRes);+ V.mm.setMode(c.mmMode);++ const bool snap = V.fresh;+ const float oct = 12.0f * static_cast<float>(c.octave);+ for (int k = 0; k < 2; ++k) {+ V.rPitch[k].to(c.semi[k] + oct + c.drift * (0.08f * V.oP[k] + 0.03f * V.walk), snap);+ V.rLvl[k].to(c.lvl[k], snap);+ V.rDuty[k].to(c.duty[k], snap);+ V.rWave[k].to(c.wave[k], snap);+ V.rMetal[k].to(c.metal[k], snap);+ }+ V.rMmCut.to(c.mmCut + c.drift * 0.15f * V.oCut, snap);+ V.rLdCut.to(c.ldCut + c.drift * 0.15f * V.oCut, snap);+ V.rNoise.to(c.noiseLvl, snap);+ const float stackGain = V.stackN > 1 ? std::pow(static_cast<float>(V.stackN), -0.4f) : 1.0f;+ V.rGain.to(c.gain * stackGain, snap);+ // Detune, Spread and Pan move a held chord too, not just the next note.+ V.rDet.to(V.stackU * c.uniDetune * 0.5f, snap);+ const float pan = std::clamp(V.panPos * c.spread + c.pan, -1.0f, 1.0f);+ V.rPanL.to(std::cos((pan + 1.0f) * 0.78539816f), snap);+ V.rPanR.to(std::sin((pan + 1.0f) * 0.78539816f), snap);+ V.fresh = false;+}++int renderVoice(Voice& V, const PartCtl& c, int from, int n, int os, double sr, float modWheel, int fadeLen,+ const float* gLfo1, float* osL, float* osR) {+ const double fsOs = sr * os;+ const double invFsOs = 1.0 / fsOs;+ V.mm.setSampleRate(fsOs);+ V.ld.setSampleRate(fsOs);+ const float velA = 1.0f - c.aVel * (1.0f - V.vel);+ const float velF = 1.0f - c.fVel * (1.0f - V.vel);+ const float vib = (c.vibSemis * modWheel + c.vibExtra) * c.lfoAmt[0];+ const double lfoInc = c.lfoHz[0] / sr;+ const float noiseA = fast_math::exp2f(-c.noiseCol * 7.0f), noiseG = 1.0f + c.noiseCol * 2.5f;+ // Low mode: Osc 2 leaves the keyboard (and the bend and vibrato) and sits three octaves below+ // middle C, Coarse / Fine and the matrix still moving it, so it can act as a modulator.+ constexpr float kO2LowKey = 60.0f - 36.0f;+ const float invFade = fadeLen > 0 ? 1.0f / static_cast<float>(fadeLen) : 1.0f;++ for (int i = from; i < n; ++i) {+ // -- a stolen voice fades out, then the caller hands it the pending note --+ float fadeG = 1.0f;+ if (V.fade > 0) {+ --V.fade;+ fadeG = static_cast<float>(V.fade) * invFade;+ if (V.fade == 0) {+ if (V.pendNote < 0) {+ V.active = V.gate = false;+ V.aenv = V.fenv = V.menv = Env{};+ }+ return i;+ }+ }+ V.pitch += (V.pitchTgt - V.pitch) * V.glideC;+ V.ex.tick(c.exAdd, c.exCoef);+ const float fe = V.fenv.tick();+ const float ae = V.aenv.tick();+ V.menv.tick();+ if (V.aenv.st == Env::Idle && V.fade == 0) {+ V.active = V.gate = false;+ return i;+ }++ // -- LFO 1 → vibrato (fade-in per voice) --+ float lv = 0.0f;+ if (vib != 0.0f) {+ const float raw = c.lfoGlobal[0] ? gLfo1[i] : V.lfo[0].step(lfoInc, c.lfoShape[0]);+ lv = raw * V.lfoFadeLvl[0] * vib;+ } else if (!c.lfoGlobal[0])+ V.lfo[0].step(lfoInc, c.lfoShape[0]); // keep the phase running+ if (V.lfoFadeLvl[0] < 1.0f) V.lfoFadeLvl[0] = std::min(1.0f, V.lfoFadeLvl[0] + V.lfoFadeInc[0]);++ const float key = V.pitch + V.rDet.next() + V.ex.bend();+ const float p1 = key + V.rPitch[0].next() + lv;+ const float p2 = (c.o2lo ? kO2LowKey : key + lv) + V.rPitch[1].next();+ const double dt1 = std::min(440.0 * fast_math::exp2f((p1 - 69.0f) * (1.0f / 12.0f)) * invFsOs, 0.45);+ const double dt2 = std::min(440.0 * fast_math::exp2f((p2 - 69.0f) * (1.0f / 12.0f)) * invFsOs, 0.45);+ const float kt = (key - 60.0f) * (1.0f / 12.0f);+ const float mmOct = V.rMmCut.next() + c.mmKey * kt + fe * c.mmEnv * velF;+ const float ldOct = V.rLdCut.next() + c.ldKey * kt + fe * c.ldEnv * velF;+ if (c.fmFilt == 0.0f) V.mm.setG(V.mm.prewarp(fast_math::exp2f(std::clamp(mmOct, 3.3f, 14.6f))));+ V.ld.setParams(fast_math::exp2f(std::clamp(ldOct, 3.3f, 14.6f)), c.ldRes);++ const float l1 = V.rLvl[0].next(), l2 = V.rLvl[1].next(), ln = V.rNoise.next();+ const float du1 = V.rDuty[0].next(), du2 = V.rDuty[1].next();+ const WaveGains w1 = waveGains(V.rWave[0].next()), w2 = waveGains(V.rWave[1].next());+ const float m1 = V.rMetal[0].next() * w1.tri, m2 = V.rMetal[1].next() * w2.tri;+ const float amp = ae * velA * V.rGain.next() * fadeG;+ const float a1 = l1 * (1.0f - c.bal[0]), b1 = l1 * c.bal[0];+ const float a2 = l2 * (1.0f - c.bal[1]), b2 = l2 * c.bal[1];+ const float an = ln * (1.0f - c.noiseBal), bn = ln * c.noiseBal;+ const float panL = V.rPanL.next(), panR = V.rPanR.next();+ float* L = osL + i * os;+ float* R = osR + i * os;+ // What this sample doesn't need: an oscillator nothing hears or uses (FM, sync, filter+ // FM), a filter nothing feeds that can't ring on its own — it would only shape the+ // −100 dB floor (no Brute feedback, resonance below the singing edge).+ const bool o1On = l1 != 0.0f || c.sync, o2On = l2 != 0.0f || c.fm21 != 0.0f || c.fmFilt != 0.0f;+ const bool quietLoop = c.brute == 0.0f;+ // A filter whose feed stopped runs on until what it holds has faded (kFilterHang quiet+ // samples), then it is reset and rests; fed again, it starts from silence.+ const bool mmFed = a1 != 0.0f || a2 != 0.0f || an != 0.0f || !quietLoop || c.mmRes >= 0.5f;+ const bool mmOn = mmFed || V.mmQuiet < kFilterHang;+ const bool ldFed = b1 != 0.0f || b2 != 0.0f || bn != 0.0f || !quietLoop || c.ldRes >= 0.5f || (mmOn && c.route < 1.0f);+ const bool ldOn = ldFed || V.ldQuiet < kFilterHang;++ for (int s = 0; s < os; ++s) {+ double d1 = dt1;+ if (c.fm21 != 0.0f) d1 = std::min(d1 * fast_math::exp2f(c.fm21 * V.o2Out), 0.45);+ float y1 = 0.0f, y2 = 0.0f;+ const float wrap1 = o1On ? oscStep(V.osc[0], d1, du1, w1, -1.0f, y1) : -1.0f;+ if (o2On) oscStep(V.osc[1], dt2, du2, w2, c.sync ? wrap1 : -1.0f, y2);+ if (m1 > 0.0f) y1 += m1 * (fold(y1, 1.0f + 3.0f * m1, V.fx1[0], V.fy1[0]) - y1);+ else V.fx1[0] = y1;+ if (m2 > 0.0f) y2 += m2 * (fold(y2, 1.0f + 3.0f * m2, V.fx1[1], V.fy1[1]) - y2);+ else V.fx1[1] = y2;+ V.o2Out = y2;++ V.noiseRng ^= V.noiseRng << 13;+ V.noiseRng ^= V.noiseRng >> 17;+ V.noiseRng ^= V.noiseRng << 5;+ const float white = static_cast<float>(V.noiseRng >> 8) * (2.0f / 16777216.0f) - 1.0f;+ V.noiseLp += noiseA * (white - V.noiseLp);+ const float nz = V.noiseLp * noiseG;++ // Brute feedback, plus a −100 dB floor so a resonant filter can sing on its own.+ const float fbS = c.brute * 0.9f * softBound(1.5f * V.fb) + 1e-5f * white;+ const float mmIn = a1 * y1 + a2 * y2 + an * nz + fbS;+ const float ldIn = b1 * y1 + b2 * y2 + bn * nz + fbS;+ float mo = 0.0f, lo = 0.0f;+ if (mmOn) {+ if (c.fmFilt != 0.0f)+ V.mm.setG(V.mm.prewarp(fast_math::exp2f(std::clamp(mmOct + c.fmFilt * y2, 3.3f, 14.6f))));+ mo = V.mm.process(mmIn);+ if (mmFed) V.mmQuiet = 0;+ else if (std::fabs(mo) > kFilterRest) V.mmQuiet = 0;+ else if (++V.mmQuiet >= kFilterHang) V.mm.reset();+ }+ if (ldOn) {+ const float li = ldIn + (1.0f - c.route) * mo;+ lo = c.ld12 ? V.ld.process12(li) : V.ld.process(li);+ if (ldFed) V.ldQuiet = 0;+ else if (std::fabs(lo) > kFilterRest) V.ldQuiet = 0;+ else if (++V.ldQuiet >= kFilterHang) V.ld.reset();+ }+ float out = lo + c.route * mo;+ V.fb = out;+ if (c.drive > 0.0f)+ out = V.sat.process(out * (1.0f + 6.0f * c.drive) * 0.6f) * (1.0f / 0.6f) / (1.0f + 1.5f * c.drive);+ const float o = out * amp;+ L[s] += o * panL;+ R[s] += o * panR;+ }+ // Extreme settings must never poison the voice.+ if (!std::isfinite(V.fb)) {+ V.mm.reset();+ V.ld.reset();+ V.sat.reset();+ V.fb = 0.0f;+ }+ }+ return n;+}++} // namespace twin+} // namespace notadiff --git a/src/native/nota.engine/src/devices/instruments/TwinVoice.h b/src/native/nota.engine/src/devices/instruments/TwinVoice.hnew file mode 100644index 00000000..4fb39d81--- /dev/null+++ b/src/native/nota.engine/src/devices/instruments/TwinVoice.h@@ -0,0 +1,328 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Twin — one voice (specs/055 US1): two oscillators, noise, the multimode and ladder+// filters, Brute feedback, drive, three envelopes and the per-voice LFO.+//+// Osc 1 ─┐ (Osc 2 hard-syncs to Osc 1, frequency-modulates Osc 1 and the multimode cutoff)+// Osc 2 ─┼─ each source's level, and its balance between the two filter inputs+// Noise ─┘+// ├─→ Multimode (LP→BP→HP→Notch) ─┬───────── route: series (into the ladder) ↔ parallel+// └─→ Ladder (12 / 24 dB) ←───────┘ ─→ Σ ─→ Brute feedback ↺ ─→ drive ─→ VCA ─→ pan+//+// Oscillators: Pentad's band-limited core (4-point polyBLEP / polyBLAMP residuals through a+// two-sample ring), so a continuous Wave can blend triangle → saw → square and hard sync stays+// clean. Metal folds the triangle share of the wave (sin folder, first-order ADAA). The voice+// runs at ×2 (×1 at 88.2 kHz and above); Twin decimates the voice sum once.+//+// Everything a voice reads arrives in a PartCtl (the part's morphed, denormalized values,+// refreshed every kCtl samples on a fixed sample grid, so a render doesn't depend on the host's+// block size); the values that would zipper ramp linearly across the kCtl samples.++#pragma once++#include "Pentad.h" // pentad:: band-limited oscillator core, Rng, hash32, Adaa+#include "dsp/math/FastMath.h"+#include "engine/NoteExpression.h"+#include "dsp/primitives/LadderFilter.h"+#include "dsp/primitives/SteinerFilter.h"++#include <cmath>+#include <cstdint>++namespace nota {+namespace twin {++constexpr int kCtl = 32; // control interval (samples)+constexpr int kFilterHang = 256; // quiet samples (oversampled) before an unfed filter rests+constexpr float kFilterRest = 1.0e-4f; // −80 dB: above the −100 dB floor an unfed filter still passes+constexpr int kMaxOs = 2; // voice oversampling++// lo · (hi/lo)^v through the fast exp2 (≈ 0.03 cent): it runs per voice per control interval.+inline double expMap(double v, double lo, double hi) {+ return lo * fast_math::exp2f(static_cast<float>(std::clamp(v, 0.0, 1.0) * std::log2(hi / lo)));+}++// ---- musical mappings (normalized → units); the card's readouts mirror these ----------+inline int coarseSemis(float v) { return std::clamp(static_cast<int>(std::lround(v * 48.0f)), 0, 48) - 24; }+inline float fineSemis(float v) { return (v - 0.5f); } // ±50 cents+inline float cutoffOct(float v) { return 4.321928f + std::clamp(v, 0.0f, 1.0f) * 9.965784f; } // log2 Hz, 20 Hz..20 kHz+inline float envAmtOct(float v) { return (v - 0.5f) * 16.0f; } // ±8 octaves+inline float attackSec(float v) { return static_cast<float>(expMap(v, 0.0005, 10.0)); }+inline float decaySec(float v) { return static_cast<float>(expMap(v, 0.003, 15.0)); }+inline float delaySec(float v) { return v < 0.002f ? 0.0f : static_cast<float>(expMap(v, 0.001, 5.0)); }+inline float glideSec(float v) { return v < 0.002f ? 0.0f : static_cast<float>(expMap(v, 0.005, 5.0)); }+inline float lfoHz(float v) { return static_cast<float>(expMap(v, 0.02, 40.0)); }+inline float fadeSec(float v) { return v < 0.002f ? 0.0f : static_cast<float>(expMap(v, 0.01, 10.0)); }+inline float dutyOf(float v) { return 0.05f + 0.9f * std::clamp(v, 0.0f, 1.0f); }+inline float partGain(float v) { return 2.0f * v * v; } // Out Volume: 0.7 ≈ unity+inline int stepOf(float v, int n) { return std::clamp(static_cast<int>(std::lround(v * (n - 1))), 0, n - 1); }++// LFO cycle lengths in beats (quarter notes) for the synced divisions: 8 bars … 1/32.+inline double syncBeats(float v) {+ static const double b[14] = {32., 16., 8., 4., 2., 1.5, 1., 0.75, 2. / 3., 0.5, 1. / 3., 0.25, 1. / 6., 0.125};+ return b[stepOf(v, 14)];+}++// Triangle → saw → square gains for Wave 0..1, the pulse trimmed to the saw's loudness.+struct WaveGains {+ float tri, saw, pul;+};+inline WaveGains waveGains(float w) {+ w = std::clamp(w, 0.0f, 1.0f);+ return {std::max(0.0f, 1.0f - 2.0f * w), 1.0f - std::fabs(2.0f * w - 1.0f), 0.6f * std::max(0.0f, 2.0f * w - 1.0f)};+}++// The part's sounding values for one control interval.+struct PartCtl {+ // oscillators+ float semi[2] = {0, 0}, wave[2] = {0.5f, 0.5f}, duty[2] = {0.5f, 0.5f}, metal[2] = {0, 0};+ float lvl[2] = {1, 0}, bal[2] = {1, 1};+ bool sync = false, o2lo = false;+ float fm21 = 0, fmFilt = 0; // octaves per unit of Osc 2+ float noiseLvl = 0, noiseCol = 0.5f, noiseBal = 1;+ // filters+ float mmCut = 14.0f, mmRes = 0, mmMode = 0, mmKey = 0, mmEnv = 0;+ float ldCut = 11.0f, ldRes = 0, ldKey = 0.5f, ldEnv = 0;+ bool ld12 = false;+ float route = 1, brute = 0, drive = 0;+ // envelopes: seconds, sustain, velocity, curve+ float fA = 0, fD = 0.1f, fS = 0.5f, fR = 0.1f, fVel = 0, fCurve = 0.5f;+ float aA = 0, aD = 0.1f, aS = 1, aR = 0.1f, aVel = 0.5f, aCurve = 0.5f;+ float mDly = 0, mA = 0, mD = 0.1f, mS = 0, mR = 0.1f, mVel = 0;+ bool mLoop = false;+ // LFO 1 (vibrato in US1; the matrix reads all three in US4)+ float lfoHz[3] = {1, 1, 1}, lfoFade[3] = {0, 0, 0}, lfoAmt[3] = {1, 1, 1};+ int lfoShape[3] = {0, 0, 0};+ float lfoSym[3] = {0.5f, 0.5f, 0.5f}, lfoCurve[3] = {1, 1, 1}; // LFO 3's Symmetry / Curve+ bool lfoGlobal[3] = {false, false, true}, lfoRetrig[3] = {false, false, false};+ float vibSemis = 0;+ // voice+ float drift = 0, uniDetune = 0, spread = 0;+ int spreadMode = 0;+ int voiceMode = 0; // Poly / Mono / Legato / Unison+ float glideSec = 0;+ bool glideLegato = false;+ int octave = 0;+ float gain = 1, pan = 0;+ // Expression (US3): the instrument-wide offsets every voice adds (wheel bend in semitones,+ // channel pressure, CC74 slide), their smoothing, and the pad's X / Z.+ float exAdd[kExprDims] = {0.0f, 0.0f, 0.0f};+ float exCoef = 1.0f;+ float vibExtra = 0.0f; // the matrix's Vibrato destination: semitones of LFO 1, per voice+ // Effects (US5): normalized values for the internal devices, and which ones are on.+ bool fxOn = true, modOn = false, dlyOn = false, revOn = false;+ int modType = 0; // Chorus / Flanger / Phaser / Ensemble+ float modRate = 0.3f, modDepth = 0.5f, modMix = 0.3f;+ float dlyTime = 0.4f, dlyDiv = 0.7f, dlyFb = 0.35f, dlyMix = 0.25f;+ bool dlySync = true, dlyPing = true;+ float revSize = 0.5f, revDamp = 0.5f, revMix = 0.2f;+};++// The sequencer's motion lanes for a control interval: side params set outright (on side A or+// B, before the morph blends them) and, optionally, the part's Morph and the expression pad.+struct MotionOverride {+ int n = 0;+ int side[4] = {}; // 0 = A, 1 = B+ int param[4] = {}; // SideParam+ float v[4] = {};+ float morph = -1.0f; // −1 = the knob's own+ float pad[3] = {-1.0f, -1.0f, -1.0f}; // the expression pad's X / Y / Z, −1 = the pad's own+};++// One live matrix route of a part for a control interval (TwinMod): depth morphed, −1..1.+// A route's depth on each side (−1..1); it morphs like a sound control: at(m) is the depth at the+// morph position m. A route to Morph is weighed at the knob's morph (it moves the morph, so it+// can't depend on where it moves it); every other route at the morph the part or voice sounds.+struct LiveRoute {+ int src;+ int dst;+ float a, b;+ float at(float m) const { return m <= 0.0f ? a : m >= 1.0f ? b : a + (b - a) * m; }+};++constexpr float kRoutePitchSt = 24.0f; // a full-depth route to a pitch destination: ±24 st+constexpr float kRouteVibratoSt = 1.0f; // … to Vibrato: ±1 st of LFO 1++// ---- envelope ------------------------------------------------------------------------+// RC segments like an analog generator: the attack charges towards a target above 1 (the+// curve sets how far: near-linear at 0, strongly exponential at 1), decay and release fall+// exponentially. The mod envelope adds a delay and can loop attack → decay while held.+struct Env {+ enum : uint8_t { Idle, Delay, Attack, Decay, Release };+ uint8_t st = Idle;+ float lvl = 0.0f;+ int32_t dly = 0;+ float aC = 1, dC = 1, rC = 1, aTgt = 1.3f, sus = 1;+ bool loop = false;++ void gateOn(int32_t delaySamples) {+ dly = delaySamples;+ st = dly > 0 ? Delay : Attack; // retrigger from the current level, no click+ }+ void gateOff() {+ if (st != Idle) st = Release;+ }+ // Per-control-interval coefficients from times in seconds.+ void setTimes(float a, float d, float s, float r, float curve, double sr, bool loopIt) {+ const float over = 0.02f + 3.0f * (1.0f - curve) * (1.0f - curve); // attack target overshoot+ aTgt = 1.0f + over;+ const double tauA = std::max(1e-5, static_cast<double>(a)) / std::log((1.0 + over) / over);+ aC = static_cast<float>(1.0 - std::exp(-1.0 / (tauA * sr)));+ dC = static_cast<float>(1.0 - std::exp(-6.9 / (std::max(1e-4, static_cast<double>(d)) * sr)));+ rC = static_cast<float>(1.0 - std::exp(-6.9 / (std::max(1e-4, static_cast<double>(r)) * sr)));+ sus = std::clamp(s, 0.0f, 1.0f);+ loop = loopIt;+ }+ float tick() {+ switch (st) {+ case Delay:+ if (--dly <= 0) st = Attack;+ break;+ case Attack:+ lvl += (aTgt - lvl) * aC;+ if (lvl >= 1.0f) {+ lvl = 1.0f;+ st = Decay;+ }+ break;+ case Decay:+ lvl += (sus - lvl) * dC;+ if (loop && std::fabs(lvl - sus) < 1e-3f) st = Attack;+ break;+ case Release:+ lvl -= lvl * rC;+ if (lvl < 3e-5f) { // ≈ −90 dB+ lvl = 0.0f;+ st = Idle;+ }+ break;+ default: break;+ }+ return lvl;+ }+};++// ---- LFO -----------------------------------------------------------------------------+// One sine-ish cycle per unit phase; the random shapes draw a new value per cycle.+inline float fastSin(float ph) { // ph 0..1 → sin(2π ph), parabolic with one refinement (≈ 0.1 % error)+ float x = ph < 0.25f ? 4.0f * ph : (ph < 0.75f ? 2.0f - 4.0f * ph : 4.0f * ph - 4.0f); // triangle, 0 at 0, peak at 0.25+ x = x * (2.0f - std::fabs(x)); // parabola through the triangle+ return x * (0.775f + 0.225f * std::fabs(x)); // refine towards a sine+}++struct Lfo {+ double ph = 0.0;+ float val = 0.0f; // the last value step() returned+ float rPrev = 0, rNext = 0;+ pentad::Rng rng;++ // Advance by inc (cycles per sample) and return the shape's value −1..1. sym moves the+ // triangle's peak (0.5 = centred); curve bends every shape as sign · |v|^curve (1 = straight).+ // Only LFO 3 has the two controls; the others pass the neutral values.+ float step(double inc, int shape, float sym = 0.5f, float curve = 1.0f) {+ ph += inc;+ if (ph >= 1.0) {+ ph -= std::floor(ph);+ rPrev = rNext;+ rNext = rng.bi();+ }+ const float p = static_cast<float>(ph);+ switch (shape) {+ case 0: val = fastSin(p); break;+ case 1:+ if (sym == 0.5f) val = p < 0.5f ? 4.0f * p - 1.0f : 3.0f - 4.0f * p;+ else val = p < sym ? 2.0f * p / sym - 1.0f : 1.0f - 2.0f * (p - sym) / (1.0f - sym);+ break;+ case 2: val = 1.0f - 2.0f * p; break;+ case 3: val = p < 0.5f ? 1.0f : -1.0f; break;+ case 4: val = rNext; break;+ default: {+ const float s = p * p * (3.0f - 2.0f * p);+ val = rPrev + (rNext - rPrev) * s;+ }+ }+ if (curve != 1.0f) val = std::copysign(std::pow(std::fabs(val), curve), val);+ return val;+ }+};++// A linear ramp across one control interval.+struct Ramp {+ float cur = 0, inc = 0;+ void to(float target, bool snap) {+ if (snap) {+ cur = target;+ inc = 0;+ } else+ inc = (target - cur) * (1.0f / kCtl);+ }+ float next() { return cur += inc; }+};++// ---- the voice ---------------------------------------------------------------------------+struct Voice {+ // allocation+ bool active = false, gate = false, hasPitch = false, fresh = true;+ bool seq = false, pendSeq = false; // played by the sequencer (its note-offs, not the keyboard's)+ int note = 60, part = 0, stackIdx = 0, stackN = 1;+ float vel = 0.8f;+ float relVel = 0.0f; // the release velocity of its note-off (0 until released, or none sent)+ uint64_t order = 0;+ int fade = 0; // samples left of a steal fade-out+ int pendNote = -1, pendStack = 0, pendStackN = 1;+ float pendVel = 0;+ bool pendGlide = false;+ float pendExpr[kExprDims] = {0.0f, 0.0f, 0.5f};+ VoiceExpr ex; // this note's bend / pressure / slide+ // pitch+ float pitch = 60, pitchTgt = 60, glideC = 1;+ // Stereo and unison: where the voice sits (-1..1 in its stack, and its pan position before+ // Spread / Pan scale it), set at the note-on; detune and pan follow the controls from there.+ float stackU = 0, panPos = 0;+ // oscillators+ pentad::Osc osc[2];+ float o2Out = 0; // Osc 2's last sample (FM into Osc 1)+ double fx1[2] = {0, 0}; // Metal folder ADAA state per oscillator+ float fy1[2] = {0, 0};+ uint32_t noiseRng = 1;+ float noiseLp = 0;+ // filters+ dsp::SteinerFilter mm;+ dsp::LadderFilter ld;+ float fb = 0; // Brute: the filter section's last output+ int mmQuiet = 0, ldQuiet = 0; // oversampled samples each filter has been unfed and silent+ pentad::Adaa sat;+ // modulation+ Env fenv, aenv, menv;+ Lfo lfo[3];+ float lfoFadeLvl[3] = {1, 1, 1}, lfoFadeInc[3] = {0, 0, 0};+ // analog drift: static spread + a slow walk+ float oP[2] = {0, 0}, oCut = 0, oEnv = 0;+ float walk = 0, walkTgt = 0;+ int walkLeft = 0;+ pentad::Rng rng;+ // ramps across the control interval+ Ramp rPitch[2], rMmCut, rLdCut, rLvl[2], rNoise, rDuty[2], rWave[2], rMetal[2], rGain;+ Ramp rDet, rPanL, rPanR; // unison detune (semitones) and the equal-power pan gains+ // The matrix (US4): when a route moves anything for this voice — a per-note source on the+ // Morph included — the voice sounds its own values, re-evaluated each interval into `own`.+ float morphOff = 0.0f; // this voice's morph offset (telemetry)+ float rnd = 0.0f; // the Random source: drawn at the note-on+ bool hasOwn = false;+ PartCtl own;+};++// Render base-rate samples [from, n) of one voice into the os-rate stereo buffers (added).+// Returns where it stopped: n, or earlier when the voice went silent or a steal fade ended+// (then, if the voice has a pending note, the caller starts it and renders on from there).+// gLfo1: LFO 1's shared values for the interval when it runs in global mode.+int renderVoice(Voice& V, const PartCtl& c, int from, int n, int os, double sr, float modWheel, int fadeLen,+ const float* gLfo1, float* osL, float* osR);++// Per-control-interval voice setup: envelope coefficients and the ramps towards this+// interval's targets.+void voiceControl(Voice& V, const PartCtl& c, double sr);++} // namespace twin+} // namespace notadiff --git a/src/native/nota.engine/src/devices/racks/RackCore.cpp b/src/native/nota.engine/src/devices/racks/RackCore.cppindex f960a070..ba142982 100644--- a/src/native/nota.engine/src/devices/racks/RackCore.cpp+++ b/src/native/nota.engine/src/devices/racks/RackCore.cpp@@ -23,6 +23,7 @@#include "devices/instruments/GrainSynth.h"#include "devices/instruments/Sampler.h"#include "devices/instruments/Mosaic.h"+#include "devices/instruments/Twin.h"#include "DrumRack.h"#include "devices/DeviceFactory.h"@@ -967,6 +968,7 @@ std::shared_ptr<Instrument> RackCore::makeInstrument(int32_t kind) {case 15: return std::make_shared<Consort>();case 16: return std::make_shared<Keys>();case 17: return std::make_shared<Mosaic>(); // empty: the program rides its state or the engine+ case 18: return std::make_shared<Twin>();case 4: return std::make_shared<DrumRack>(); // nested Drum Rack (specs/041)default: return nullptr; // -1 = no instrument (effect rack); plugins are a follow-up}diff --git a/src/native/nota.engine/src/devices/racks/RackInstrument.cpp b/src/native/nota.engine/src/devices/racks/RackInstrument.cppindex 05cd5e8a..d513b896 100644--- a/src/native/nota.engine/src/devices/racks/RackInstrument.cpp+++ b/src/native/nota.engine/src/devices/racks/RackInstrument.cpp@@ -207,7 +207,11 @@ void RackInstrument::fanOff(int32_t pitch) {syncChains();const int32_t n = static_cast<int32_t>(st->chains.size());for (int32_t ci = 0; ci < n; ++ci)- if (st->chains[ci].instrument && !midiChainAt(ci)) st->chains[ci].instrument->noteOff(pitch);+ if (st->chains[ci].instrument && !midiChainAt(ci)) {+ if (relVel_ > 0.0f) st->chains[ci].instrument->noteOffVelocity(pitch, relVel_);+ else+ st->chains[ci].instrument->noteOff(pitch);+ }}void RackInstrument::endGlide() {@@ -271,6 +275,12 @@ void RackInstrument::noteOn(int32_t pitch, float velocity) {m.glideTotal = m.glideLeft = glide ? std::max<int64_t>(1, std::llround(ms * 0.001 * sampleRate_)) : 0;}+void RackInstrument::noteOffVelocity(int32_t pitch, float velocity) {+ relVel_ = velocity;+ noteOff(pitch);+ relVel_ = 0.0f;+}+void RackInstrument::noteOff(int32_t pitch) {if (pitch < 0 || pitch > 127) return;syncMono();diff --git a/src/native/nota.engine/src/devices/racks/RackInstrument.h b/src/native/nota.engine/src/devices/racks/RackInstrument.hindex 1b7716c8..4d4428c7 100644--- a/src/native/nota.engine/src/devices/racks/RackInstrument.h+++ b/src/native/nota.engine/src/devices/racks/RackInstrument.h@@ -48,6 +48,7 @@ class RackInstrument : public Instrument, public RackCore {// ---- note fan-out: a note reaches a chain only if it's inside its key/vel zone --void noteOn(int32_t pitch, float velocity) override;void noteOff(int32_t pitch) override;+ void noteOffVelocity(int32_t pitch, float velocity) override; // the chains get it toovoid allNotesOff() override;// Expression goes to every chain: one whose zone kept the note out isn't holding the// pitch, so it ignores it.@@ -99,6 +100,7 @@ class RackInstrument : public Instrument, public RackCore {// that take per-note bend start bent to the previous pitch and glide back (mono).void fanOn(int32_t pitch, float velocity, int32_t glideFrom);void fanOff(int32_t pitch);+ float relVel_ = 0.0f; // the release velocity of the note-off being fanned out (audio thread)void monoRemove(int32_t pitch);void syncMono(); // mono switched since the last call: reconcile the sounding keysvoid endGlide(); // a glide stops half-way: the sounding note returns to its own pitchdiff --git a/src/native/nota.engine/src/dsp/primitives/LadderFilter.cpp b/src/native/nota.engine/src/dsp/primitives/LadderFilter.cppindex dc71dcaa..4630b99b 100644--- a/src/native/nota.engine/src/dsp/primitives/LadderFilter.cpp+++ b/src/native/nota.engine/src/dsp/primitives/LadderFilter.cpp@@ -13,19 +13,40 @@namespace nota {namespace dsp {+namespace {++// The loop gain at which the ladder starts to self-oscillate, against its one-pole coefficient+// (measured: −50 dB steady oscillation from a −100 dB noise floor, one sub-step). A digital+// one-pole adds phase lag as its coefficient grows, so the edge climbs from ≈ 4.2 (the analog+// value) towards the top of the range, then falls again near Nyquist; a fixed feedback would+// leave high cutoffs unable to sing.+double criticalFeedback(double f) {+ static const double kF[] = {0.0, 0.0088, 0.026, 0.085, 0.162, 0.298, 0.438, 0.507, 0.618, 0.654, 0.757, 0.829};+ static const double kG[] = {4.56, 4.21, 4.16, 4.39, 4.82, 5.88, 7.73, 9.17, 13.08, 15.1, 7.29, 3.98};+ constexpr int n = sizeof kF / sizeof kF[0];+ if (f >= kF[n - 1]) return kG[n - 1];+ int i = 1;+ while (f > kF[i]) ++i;+ const double t = (f - kF[i - 1]) / (kF[i] - kF[i - 1]);+ return kG[i - 1] + (kG[i] - kG[i - 1]) * t;+}++} // namespace+void LadderFilter::setSampleRate(double sr) noexcept {sr_ = sr > 0.0 ? sr : 44100.0;}void LadderFilter::setParams(float fc, float reso) NOTA_RT_SAFE {- const double srOs = sr_ * 2.0;+ const double srOs = sr_ * os_;// Poles sit a touch above the knob so the passband stays open while the// resonant peak tracks the cutoff (proven in Monolith).const double fpole = std::min<double>(fc * 1.35, srOs * 0.45);- double f = 1.0 - std::exp(-2.0 * 3.14159265358979 * fpole / srOs);+ // fast exp2 (≈ 0.03 cent): this runs per sample when a caller sweeps the cutoff.+ double f = 1.0 - fast_math::exp2f(static_cast<float>(-2.0 * 3.14159265358979 * 1.4426950408889634 * fpole / srOs));f_ = std::clamp(f, 0.0, 0.995);reso_ = std::clamp<double>(reso, 0.0, 1.0);- fb_ = reso_ * 4.2; // self-oscillation at max+ fb_ = reso_ * criticalFeedback(f_) * 1.04; // just past the edge at max: self-oscillates at any pitch}void LadderFilter::reset() noexcept {diff --git a/src/native/nota.engine/src/dsp/primitives/LadderFilter.h b/src/native/nota.engine/src/dsp/primitives/LadderFilter.hindex 7d7473ff..67c80372 100644--- a/src/native/nota.engine/src/dsp/primitives/LadderFilter.h+++ b/src/native/nota.engine/src/dsp/primitives/LadderFilter.h@@ -2,10 +2,12 @@// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//// LadderFilter — 4-pole zero-delay-feedback transistor ladder.-// Monolith's proven tanh state-difference model (2x internally oversampled,-// self-oscillates at max emphasis, resonant passband makeup + optional bass-// compensation), lifted verbatim into the shared primitive with fast_math tanh.-// Shared by Monolith, Consort and Pentad.+// Monolith's tanh state-difference model (2x internally oversampled by default,+// resonant passband makeup + optional bass compensation), lifted into the shared+// primitive with fast_math tanh. The resonance feedback follows the measured edge of+// self-oscillation for the current coefficient, so full resonance sings at any pitch.+// Nota Twin uses it, with the 2-pole tap; Monolith, Consort and Pentad still run their own+// copies of the model.#pragma once@@ -23,15 +25,26 @@ class LadderFilter {LadderFilter() = default;void setSampleRate(double sr) noexcept;+ // The ladder runs 2 sub-steps per sample by default; a caller that already oversamples+ // (Nota Twin's voice runs at ×2) can take 1, at its own oversampled rate.+ void setInternalOversampling(int n) noexcept { os_ = n > 1 ? 2 : 1; }// fc in Hz, reso in [0, 1] (1 = self-oscillation).void setParams(float fc, float reso) NOTA_RT_SAFE;void reset() noexcept;float process(float x, bool bassComp = false) NOTA_RT_SAFE;+ // The same ladder with its output taken after the second pole: a 12 dB/oct slope that keeps+ // the 4-pole feedback loop, so resonance and self-oscillation behave as in process()+ // (Nota Twin's 12/24 switch).+ float process12(float x, bool bassComp = false) NOTA_RT_SAFE;private:+ void step(float x) NOTA_RT_SAFE;+ float makeup(double tap, float x, bool bassComp) const NOTA_RT_SAFE;+double sr_ = 44100.0;- double f_ = 0.0; // one-pole coefficient at 2x rate+ int os_ = 2; // internal sub-steps per sample+ double f_ = 0.0; // one-pole coefficient at the internal ratedouble fb_ = 0.0; // resonance feedback amountdouble reso_ = 0.0;double l1_ = 0.0, l2_ = 0.0, l3_ = 0.0, l4_ = 0.0;@@ -39,19 +52,33 @@ class LadderFilter {// Per-sample hot path: inline, so callers in other TUs inline it (no LTO).-inline float LadderFilter::process(float x, bool bassComp) NOTA_RT_SAFE {+// One sample through the four poles (os_ sub-steps), feedback taken from the last pole.+inline void LadderFilter::step(float x) NOTA_RT_SAFE {const double f = f_, fb = fb_;- for (int os = 0; os < 2; ++os) {+ for (int os = 0; os < os_; ++os) {const double in = x - fb * fast_math::tanhPrecise(static_cast<float>(l4_));l1_ += f * (fast_math::tanhPrecise(static_cast<float>(in)) - fast_math::tanhPrecise(static_cast<float>(l1_)));l2_ += f * (fast_math::tanhPrecise(static_cast<float>(l1_)) - fast_math::tanhPrecise(static_cast<float>(l2_)));l3_ += f * (fast_math::tanhPrecise(static_cast<float>(l2_)) - fast_math::tanhPrecise(static_cast<float>(l3_)));l4_ += f * (fast_math::tanhPrecise(static_cast<float>(l3_)) - fast_math::tanhPrecise(static_cast<float>(l4_)));}- double y = l4_ * (1.0 + reso_ * 0.7); // makeup for resonant passband loss+}++inline float LadderFilter::makeup(double tap, float x, bool bassComp) const NOTA_RT_SAFE {+ double y = tap * (1.0 + reso_ * 0.7); // makeup for resonant passband lossif (bassComp) y += x * (reso_ * 0.20); // restore low end lost to resonancereturn static_cast<float>(y);}+inline float LadderFilter::process(float x, bool bassComp) NOTA_RT_SAFE {+ step(x);+ return makeup(l4_, x, bassComp);+}++inline float LadderFilter::process12(float x, bool bassComp) NOTA_RT_SAFE {+ step(x);+ return makeup(l2_, x, bassComp);+}+} // namespace dsp} // namespace notadiff --git a/src/native/nota.engine/src/dsp/primitives/SteinerFilter.h b/src/native/nota.engine/src/dsp/primitives/SteinerFilter.hnew file mode 100644index 00000000..d27a2d4e--- /dev/null+++ b/src/native/nota.engine/src/dsp/primitives/SteinerFilter.h@@ -0,0 +1,104 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// SteinerFilter — a 12 dB/oct multimode filter in the Steiner-Parker spirit: one resonant+// 2-pole core whose response sweeps continuously LP → BP → HP → Notch, with a dirty, diode-like+// input stage and a resonance that self-oscillates. Nota Twin's multimode filter (specs/055 R5).+//+// The core is a zero-delay-feedback state-variable filter (Cytomic TPT form). The Steiner+// circuit gets its modes by injecting the input at its low-, band- or high-pass node; for a+// linear 2-pole that equals mixing the three outputs, so the mode is a crossfade of outputs+// and the character comes from the non-linearities instead: the input runs through a soft+// diode pair, and the band-pass state is softly bounded every sample. Past full resonance the+// damping goes slightly negative, so the filter self-oscillates; the bounded state keeps that+// oscillation at a steady level instead of growing.+//+// Real-time safe: no allocation, no tables. The caller may change the cutoff every sample+// (audio-rate FM): setG takes a prewarped coefficient and refreshes the ZDF coefficients; the+// per-sample cost is then one divide and one sqrt.++#pragma once++#include <algorithm>+#include <cmath>++#include "dsp/core/RtAttributes.h"+#include "dsp/math/FastMath.h"++namespace nota {+namespace dsp {++class SteinerFilter {+ public:+ SteinerFilter() = default;++ void setSampleRate(double sr) noexcept { sr_ = sr > 0.0 ? sr : 44100.0; }+ // fc in Hz, reso 0..1 (1 = self-oscillation), mode 0..1 (LP → BP → HP → Notch).+ void setParams(float fc, float reso, float mode) NOTA_RT_SAFE {+ setG(prewarp(fc));+ setReso(reso);+ setMode(mode);+ }+ // The bilinear-prewarped coefficient for fc at this rate.+ float prewarp(float fc) const NOTA_RT_SAFE {+ const float w = 3.14159265f * std::clamp(fc, 10.0f, static_cast<float>(sr_ * 0.45)) / static_cast<float>(sr_);+ return fast_math::tanPrewarp(w);+ }+ void setG(float g) NOTA_RT_SAFE {+ g_ = g;+ coefs();+ }+ void setReso(float reso) NOTA_RT_SAFE {+ const float r = std::clamp(reso, 0.0f, 1.0f);+ k_ = 2.0f - 2.04f * r; // −0.04 at the top: just past the edge, so it sings+ coefs();+ }+ void setMode(float mode) NOTA_RT_SAFE {+ const float m = std::clamp(mode, 0.0f, 1.0f) * 3.0f;+ // Output weights for the three segments; band-pass is lifted so its level sits with the others.+ constexpr float kBp = 1.6f;+ if (m < 1.0f) {+ wLp_ = 1.0f - m, wBp_ = m * kBp, wHp_ = 0.0f;+ } else if (m < 2.0f) {+ const float t = m - 1.0f;+ wLp_ = 0.0f, wBp_ = (1.0f - t) * kBp, wHp_ = t;+ } else {+ const float t = m - 2.0f; // HP → notch (LP + HP)+ wLp_ = t, wBp_ = 0.0f, wHp_ = 1.0f;+ }+ }+ void reset() noexcept { ic1_ = ic2_ = 0.0f; }++ float process(float x) NOTA_RT_SAFE {+ // Diode-pair input: unity for small signals, rounding off the peaks of a hot mix.+ const float xin = x / (1.0f + 0.25f * std::fabs(x));+ const float k = k_, a1 = a1_, a2 = a2_, a3 = a3_;+ const float v3 = xin - ic2_;+ const float v1 = a1 * ic1_ + a2 * v3; // band-pass+ const float v2 = ic2_ + a2 * ic1_ + a3 * v3; // low-pass+ ic1_ = bound(2.0f * v1 - ic1_);+ ic2_ = 2.0f * v2 - ic2_;+ const float hp = xin - k * v1 - v2;+ return wLp_ * v2 + wBp_ * v1 + wHp_ * hp;+ }++ private:+ // The TPT coefficients, recomputed when the cutoff or resonance moves (not per sample).+ void coefs() NOTA_RT_SAFE {+ a1_ = 1.0f / (1.0f + g_ * (g_ + k_));+ a2_ = g_ * a1_;+ a3_ = g_ * a2_;+ }+ // Smooth, odd, monotonic and bounded (±4): within 1 % of linear below 0.6, so ordinary+ // signals stay clean and only a self-oscillating or overdriven state is held in.+ static float bound(float s) NOTA_RT_SAFE { return s / std::sqrt(1.0f + s * s * (1.0f / 16.0f)); }++ double sr_ = 44100.0;+ float g_ = 0.5f, k_ = 2.0f;+ float a1_ = 1.0f / 3.25f, a2_ = 0.5f / 3.25f, a3_ = 0.25f / 3.25f;+ float wLp_ = 1.0f, wBp_ = 0.0f, wHp_ = 0.0f;+ float ic1_ = 0.0f, ic2_ = 0.0f;+};++} // namespace dsp+} // namespace notadiff --git a/src/native/nota.engine/src/engine/Audition.cpp b/src/native/nota.engine/src/engine/Audition.cppindex d71985b7..32736f75 100644--- a/src/native/nota.engine/src/engine/Audition.cpp+++ b/src/native/nota.engine/src/engine/Audition.cpp@@ -152,6 +152,12 @@ bool AuditionRig::setMosaicProgram(const std::string& text, int32_t timeoutMs) {return false;}+bool AuditionRig::instrumentState(const uint8_t* data, int32_t size) {+ if (!inst_ || kit_) return false;+ inst_->setState(data, size);+ return true;+}+bool AuditionRig::setSamplerSample(const std::string& path, int32_t rootNote) {if (auto* grain = dynamic_cast<GrainSynth*>(inst_.get())) {auto buf = path.empty() ? nullptr : decodeAudioFile(path);diff --git a/src/native/nota.engine/src/engine/Audition.h b/src/native/nota.engine/src/engine/Audition.hindex c72b71ec..a317c845 100644--- a/src/native/nota.engine/src/engine/Audition.h+++ b/src/native/nota.engine/src/engine/Audition.h@@ -61,6 +61,8 @@ class AuditionRig {// Nota Mosaic's program; waits (up to timeoutMs) until its samples are in, so the// offline render that follows hears them. False when the instrument isn't a Mosaic.bool setMosaicProgram(const std::string& text, int32_t timeoutMs = 20000);+ // The instrument's state blob (Instrument::setState), e.g. a Nota Twin preset's patterns.+ bool instrumentState(const uint8_t* data, int32_t size);bool setSourceFile(const std::string& path, double maxSeconds);// Mixes another rig's rendered result into this rig's source (a demo track's part).bool addSourceFrom(const AuditionRig& part, float gain);diff --git a/src/native/nota.engine/src/engine/Engine.cpp b/src/native/nota.engine/src/engine/Engine.cppindex c1215679..870fcaed 100644--- a/src/native/nota.engine/src/engine/Engine.cpp+++ b/src/native/nota.engine/src/engine/Engine.cpp@@ -1012,6 +1012,22 @@ bool Engine::applyMix(const MixChange& c, bool after) {eq->setState(st.data(), static_cast<int32_t>(st.size()));return true;}+ if (c.kind == MixKind::InstrumentEdit) { // an instrument's edit state (sequencer patterns)+ Instrument* inst = editStateInstrument(c.trackId, c.deviceIndex, c.paramIndex);+ const auto at = static_cast<size_t>(v);+ if (!inst || at >= noteStates_.size()) return false; // gone: skip+ const auto& st = noteStates_[at];+ inst->setEditState(st.data(), static_cast<int32_t>(st.size()));+ return true;+ }+ if (c.kind == MixKind::InstrumentState) { // a rack chain instrument's whole state+ Instrument* inst = editStateInstrument(c.trackId, c.deviceIndex, c.paramIndex);+ const auto at = static_cast<size_t>(v);+ if (!inst || at >= noteStates_.size()) return false; // gone: skip+ const auto& st = noteStates_[at];+ inst->setState(st.data(), static_cast<int32_t>(st.size()));+ return true;+ }if (c.kind == MixKind::MasterVolume) {setMasterVolume(v);return true;@@ -1217,6 +1233,7 @@ void Engine::clearUndoHistory() {// them here frees nothing the audio thread can still be reading.undoStack_.clear();redoStack_.clear();+ compactNoteStates(true); // nothing refers to the saved states any moremixGestures_.clear(); // a gesture can't outlive the history it would land intouchGestures_.clear();undoGroupDepth_ = 0;diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.hindex 02b5520a..daaab7d6 100644--- a/src/native/nota.engine/src/engine/Engine.h+++ b/src/native/nota.engine/src/engine/Engine.h@@ -758,12 +758,21 @@ class Engine {int32_t addConsortTrack(); // built-in Nota Consort (paraphonic semi-modular, kind 15)int32_t addKeysTrack(); // built-in Nota Keys (modelled electric piano, kind 16)int32_t addMosaicTrack(); // built-in Nota Mosaic (multisample instrument, kind 17)+ int32_t addTwinTrack(); // built-in Nota Twin (two-part morphing analog poly, kind 18)// Nota Mosaic's program (see Mosaic.h): set parses + starts loading, get returns the text.bool mosaicSetProgram(int32_t trackId, const std::string& text, bool checkpoint);std::string mosaicProgram(int32_t trackId) const;bool mosaicStatus(int32_t trackId, NotaMosaicStatus* out) const;int64_t mosaicZoneSampleId(int32_t trackId, int32_t zone) const;void instrumentAction(int32_t trackId, int32_t id, int32_t iarg, float farg); // UI editing channel+ void instrumentActionUndoable(Instrument& inst, int32_t trackId, int32_t deviceIndex, int32_t chain, int32_t id,+ int32_t iarg, float farg); // the action, plus its undo step when the edit state changed+ bool instrumentSetStateUndoable(int32_t trackId, int32_t deviceIndex, int32_t chain, const uint8_t* data,+ int32_t size); // chain -1: the track's instrument; else that chain of the rack at deviceIndex+ Instrument* editStateInstrument(int32_t trackId, int32_t deviceIndex, int32_t chain) const;+ void pushInstrumentEdit(int32_t trackId, int32_t deviceIndex, int32_t chain, std::vector<uint8_t> before,+ std::vector<uint8_t> after, MixKind kind = MixKind::InstrumentEdit);+ bool recordInstrumentState(int32_t trackId, int32_t deviceIndex, int32_t chain, const uint8_t* before, int32_t size);bool setRhythmVoiceSample(int32_t trackId, int32_t voice, const std::string& path); // Phase 2bool rhythmVoiceInfo(int32_t trackId, int32_t voice, NotaSamplerInfo* out) const; // sample id per voiceint32_t rhythmVoiceSource(int32_t trackId, int32_t voice) const; // 0 Synth, 1 Sample@@ -1279,7 +1288,7 @@ class Engine {// Live notes (computer keyboard, gamepad, MIDI). Producers on different threads// serialize on liveMidiMx_; the audio thread only pops (AR-6).void noteOn(int32_t pitch, float velocity);- void noteOff(int32_t pitch);+ void noteOff(int32_t pitch, float releaseVelocity = 0.0f); // 0 = none// Per-note expression for live notes (MPE, NoteExpression.h): dim = ExprDim, pitch −1 =// the whole instrument. Reaches the same tracks as live notes do.void noteExpression(int32_t pitch, int32_t dim, float value);@@ -1290,7 +1299,7 @@ class Engine {// Live notes addressed to one track (Nota Remote). Callable from any thread: producers// serialize on remoteMidiMx_; the audio thread only pops (AR-6).void trackNoteOn(int32_t trackId, int32_t pitch, float velocity);- void trackNoteOff(int32_t trackId, int32_t pitch);+ void trackNoteOff(int32_t trackId, int32_t pitch, float releaseVelocity = 0.0f); // 0 = nonevoid trackNoteExpression(int32_t trackId, int32_t pitch, int32_t dim, float value);// Audition target: live notes also reach this track even when it isn't armed// (for clicking rack/drum pads). -1 = none. Lock-free.@@ -1580,6 +1589,7 @@ class Engine {Engine* e = nullptr;void mpeNoteOn(int32_t pitch, float velocity) override { e->noteOn(pitch, velocity); }void mpeNoteOff(int32_t pitch) override { e->noteOff(pitch); }+ void mpeNoteOffVelocity(int32_t pitch, float velocity) override { e->noteOff(pitch, velocity); }void mpeExpression(int32_t pitch, int32_t dim, float value) override { e->noteExpression(pitch, dim, value); }void mpeController(int32_t ctl, float value) override { e->controller(ctl, value); }};@@ -1812,6 +1822,8 @@ class Engine {// The EQ-8 annotation states undo steps point at (specs/049): append-only, 0 = none. A step// holds the indices of the device's whole state before and after the edit.std::vector<std::vector<uint8_t>> noteStates_ = std::vector<std::vector<uint8_t>>(1);+ size_t noteStatesKept_ = 1; // its size after the last compaction+ void compactNoteStates(bool force = false);bool applyMix(const MixChange& c, bool after); // write before/after; false = gonestatic void mergeMix(std::vector<MixChange>& into, const std::vector<MixChange>& later);static constexpr size_t kMaxUndoDepth = 128;@@ -2502,6 +2514,10 @@ class Engine {if (routeSlotTrackId_[s].load(std::memory_order_relaxed) == trackId) return true;return false;}++ // Built-in instruments' default param values, one fresh instance per kind+ // (instrumentParamDefault). Message thread only.+ mutable std::unordered_map<int32_t, std::vector<float>> instrumentDefaults_;};} // namespace notadiff --git a/src/native/nota.engine/src/engine/EngineTypes.h b/src/native/nota.engine/src/engine/EngineTypes.hindex 6f40ca11..fdd5c443 100644--- a/src/native/nota.engine/src/engine/EngineTypes.h+++ b/src/native/nota.engine/src/engine/EngineTypes.h@@ -107,7 +107,10 @@ enum class MixKind : int32_t {PluginParam = 5,PresetTag = 6, // a device's preset tag (specs/048): deviceIndex as above, paramIndex = the surfaceDeviceNotes = 7, // an EQ-8's band labels and notes (specs/049): the value indexes Engine::noteStates_- TrackSend = 8 // rejected (specs/069): a send level is not an undo step. deviceIndex would be the bus.+ TrackSend = 8, // rejected (specs/069): a send level is not an undo step. deviceIndex would be the bus.+ InstrumentEdit = 9, // a track instrument's edit state (Instrument::editState): the value indexes Engine::noteStates_+ InstrumentState = 10 // a rack chain instrument's whole state (params too, which have no undo target of their+ // own there): the value indexes Engine::noteStates_; deviceIndex the rack, paramIndex the chain};struct MixTarget {MixKind kind;diff --git a/src/native/nota.engine/src/engine/Engine_Devices.cpp b/src/native/nota.engine/src/engine/Engine_Devices.cppindex 902132a4..064b0bf7 100644--- a/src/native/nota.engine/src/engine/Engine_Devices.cpp+++ b/src/native/nota.engine/src/engine/Engine_Devices.cpp@@ -47,6 +47,7 @@#include "devices/instruments/Consort.h"#include "devices/instruments/Keys.h"#include "devices/instruments/Mosaic.h"+#include "devices/instruments/Twin.h"#include "devices/instruments/GrainSynth.h"#include "bridge/PluginHostBridge.h"#include "devices/racks/RackDevice.h"@@ -257,6 +258,18 @@ int32_t Engine::addKeysTrack() {return id;}+int32_t Engine::addTwinTrack() {+ auto g = std::make_shared<Graph>(*authoring_);+ const int32_t id = nextTrackId_++;+ auto track = std::make_shared<Track>(id, TrackType::Instrument);+ auto inst = std::make_shared<Twin>();+ inst->setSampleRate(transport_.sampleRate());+ track->instrument = inst;+ g->tracks.push_back(track);+ publish(g);+ return id;+}+int32_t Engine::addMosaicTrack() {auto g = std::make_shared<Graph>(*authoring_);const int32_t id = nextTrackId_++;@@ -322,7 +335,101 @@ int64_t Engine::mosaicZoneSampleId(int32_t trackId, int32_t zone) const {// instrument object is stable across snapshots, so this mutates it in place (message thread).void Engine::instrumentAction(int32_t trackId, int32_t id, int32_t iarg, float farg) {auto t = findTrackAuthoring(trackId);- if (t && t->instrument) t->instrument->action(id, iarg, farg);+ if (!t || !t->instrument) return;+ instrumentActionUndoable(*t->instrument, trackId, -1, -1, id, iarg, farg);+}++// The instrument an edit-state undo step addresses: chain >= 0 is chain `chain` of the rack at+// deviceIndex (MixChange's deviceIndex / paramIndex), -1 the track's own instrument.+Instrument* Engine::editStateInstrument(int32_t trackId, int32_t deviceIndex, int32_t chain) const {+ if (chain >= 0) {+ auto* r = rackCoreAt(trackId, deviceIndex);+ return r ? r->chainInstrument(chain) : nullptr;+ }+ auto t = findTrackAuthoring(trackId);+ return t ? t->instrument.get() : nullptr;+}++// A change of an instrument's edit state is one mix-only undo step swapping it (as setEqBandText+// does); nothing when it didn't change, or the instrument keeps none.+void Engine::pushInstrumentEdit(int32_t trackId, int32_t deviceIndex, int32_t chain, std::vector<uint8_t> before,+ std::vector<uint8_t> after, MixKind kind) {+ if (before.empty() || after == before) return;+ redoStack_.clear();+ // Inside an open undo group (a whole pattern written step by step), the edits of one+ // instrument fold into the group's entry for it: the first `before`, the latest `after`.+ // So a long run of actions is one entry and can't push the group's start out of the history.+ if (undoGroupDepth_ > 0 && undoStack_.size() > undoGroupBase_) {+ for (auto it = undoStack_.begin() + static_cast<std::ptrdiff_t>(undoGroupBase_); it != undoStack_.end(); ++it)+ for (auto& m : it->mix)+ if (m.kind == kind && m.trackId == trackId && m.deviceIndex == deviceIndex &&+ m.paramIndex == chain) {+ noteStates_[static_cast<size_t>(m.after)] = std::move(after);+ return;+ }+ }+ noteStates_.push_back(std::move(before));+ noteStates_.push_back(std::move(after));+ const auto at = static_cast<float>(noteStates_.size() - 2);+ undoStack_.push_back({nullptr, {MixChange{kind, trackId, at, at + 1.0f, deviceIndex, chain}}});+ if (undoStack_.size() > kMaxUndoDepth) {+ undoStack_.erase(undoStack_.begin());+ if (undoGroupDepth_ > 0 && undoGroupBase_ > 0) --undoGroupBase_;+ }+ compactNoteStates();+}++// The saved states (EQ-8 notes, instrument edit states) only the undo and redo history refers to:+// once the store has grown well past what the history still holds, the rest is dropped and the+// history's indices are renumbered. Index 0 stays the empty state.+void Engine::compactNoteStates(bool force) {+ if (!force && noteStates_.size() < std::max<size_t>(1024, 2 * noteStatesKept_)) return;+ std::vector<std::vector<uint8_t>> kept(1);+ std::unordered_map<size_t, size_t> remap;+ auto keep = [&](float& v) {+ const auto at = static_cast<size_t>(v);+ if (at == 0 || at >= noteStates_.size()) return;+ auto [it, fresh] = remap.try_emplace(at, kept.size());+ if (fresh) kept.push_back(std::move(noteStates_[at]));+ v = static_cast<float>(it->second);+ };+ for (auto* stack : {&undoStack_, &redoStack_})+ for (auto& e : *stack)+ for (auto& m : e.mix)+ if (m.kind == MixKind::InstrumentEdit || m.kind == MixKind::InstrumentState || m.kind == MixKind::DeviceNotes)+ keep(m.before), keep(m.after);+ noteStates_ = std::move(kept);+ noteStatesKept_ = noteStates_.size();+}++void Engine::instrumentActionUndoable(Instrument& inst, int32_t trackId, int32_t deviceIndex, int32_t chain,+ int32_t id, int32_t iarg, float farg) {+ auto before = inst.editState();+ inst.action(id, iarg, farg);+ if (!before.empty()) pushInstrumentEdit(trackId, deviceIndex, chain, std::move(before), inst.editState());+}++// An edit of a rack chain instrument made by plain param writes (a Twin's side or part copy, a+// preset): its params have no undo target of their own, so the step swaps the whole state the+// caller read before the edit for the one it has now.+bool Engine::recordInstrumentState(int32_t trackId, int32_t deviceIndex, int32_t chain, const uint8_t* before, int32_t size) {+ Instrument* inst = chain >= 0 ? editStateInstrument(trackId, deviceIndex, chain) : nullptr;+ if (!inst || !before || size <= 0) return false;+ pushInstrumentEdit(trackId, deviceIndex, chain, std::vector<uint8_t>(before, before + size), inst->getState(),+ MixKind::InstrumentState);+ return true;+}++// Loads a state blob into an instrument (a preset's patterns) with what it changes in the edit+// state as an undo step, so undoing the preset brings the old sequence back with the old sound.+bool Engine::instrumentSetStateUndoable(int32_t trackId, int32_t deviceIndex, int32_t chain, const uint8_t* data,+ int32_t size) {+ Instrument* inst = editStateInstrument(trackId, deviceIndex, chain);+ if (!inst || !data || size <= 0) return false;+ auto before = inst->editState();+ inst->setState(data, size);+ pushInstrumentEdit(trackId, deviceIndex, chain, std::move(before), inst->editState());+ return true;}// Nota Rhythm Phase 2: load a one-shot into one drum voice. Clones the instrument (so the@@ -1383,9 +1490,20 @@ float Engine::builtinDeviceParamDefault(int32_t kind, int32_t p) const {float Engine::instrumentParamDefault(int32_t t, int32_t p) const {auto tr = findTrackAuthoring(t);if (!tr || !tr->instrument) return 0.0f;- if (tr->instrument->kind() < 0) return tr->instrument->pluginParamGet(p); // plugin- auto fresh = makeBuiltinInstrument(tr->instrument->kind());- return fresh ? fresh->pluginParamGet(p) : tr->instrument->pluginParamGet(p);+ const int32_t kind = tr->instrument->kind();+ if (kind < 0) return tr->instrument->pluginParamGet(p); // plugin+ // A fresh instance's values, read once per kind: a preset asks for every param it doesn't+ // name, and building an instrument per question (Nota Twin: ~900, each with its effect+ // devices) made applying a preset take tens of milliseconds. Message thread only.+ auto it = instrumentDefaults_.find(kind);+ if (it == instrumentDefaults_.end()) {+ auto fresh = makeBuiltinInstrument(kind);+ if (!fresh) return tr->instrument->pluginParamGet(p);+ std::vector<float> d(static_cast<size_t>(fresh->pluginParamCount()));+ for (size_t i = 0; i < d.size(); ++i) d[i] = fresh->pluginParamGet(static_cast<int32_t>(i));+ it = instrumentDefaults_.emplace(kind, std::move(d)).first;+ }+ return p >= 0 && static_cast<size_t>(p) < it->second.size() ? it->second[static_cast<size_t>(p)] : tr->instrument->pluginParamGet(p);}float Engine::midiEffectParamDefault(int32_t t, int32_t i, int32_t p) const {auto* m = midiDeviceAt(t, i);@@ -1484,6 +1602,7 @@ bool Engine::setEqBandText(if (undoGroupDepth_ > 0 && undoGroupBase_ > 0) --undoGroupBase_;}redoStack_.clear();+ compactNoteStates();return true;}diff --git a/src/native/nota.engine/src/engine/Engine_Rack.cpp b/src/native/nota.engine/src/engine/Engine_Rack.cppindex 4b6e54f1..a976af88 100644--- a/src/native/nota.engine/src/engine/Engine_Rack.cpp+++ b/src/native/nota.engine/src/engine/Engine_Rack.cpp@@ -243,6 +243,7 @@ static std::shared_ptr<RackInstrument> forkRackInstrument(const RackInstrument&r->pedalDown.store(src.pedalDown.load(rl), rl);r->pedalHeld[0].store(src.pedalHeld[0].load(rl), rl);r->pedalHeld[1].store(src.pedalHeld[1].load(rl), rl);+ for (int p = 0; p < 128; ++p) r->pedalRelVel[p].store(src.pedalRelVel[p].load(rl), rl);for (int i = 0; i < kCtlCount; ++i) r->deliveredCtl[i].store(src.deliveredCtl[i].load(rl), rl);return r;}@@ -1224,7 +1225,7 @@ int32_t Engine::rackChainInstrumentHeldNotes(int32_t t, int32_t di, int32_t c, ivoid Engine::rackChainInstrumentAction(int32_t t, int32_t di, int32_t c, int32_t id, int32_t iarg, float farg) {auto* r = rackCoreAt(t, di);Instrument* inst = r ? r->chainInstrument(c) : nullptr;- if (inst) inst->action(id, iarg, farg);+ if (inst) instrumentActionUndoable(*inst, t, di, c, id, iarg, farg);}void Engine::rackOpenChainInstrumentEditor(int32_t t, int32_t di, int32_t c) {auto* r = rackCoreAt(t, di);diff --git a/src/native/nota.engine/src/engine/Engine_Recording.cpp b/src/native/nota.engine/src/engine/Engine_Recording.cppindex 5a277cd9..85ef291a 100644--- a/src/native/nota.engine/src/engine/Engine_Recording.cpp+++ b/src/native/nota.engine/src/engine/Engine_Recording.cpp@@ -223,10 +223,10 @@ void Engine::noteOn(int32_t pitch, float velocity) {}if (pitch >= 0 && pitch < 128) liveHeld_[pitch >> 5].fetch_or(1u << (pitch & 31), std::memory_order_relaxed);}-void Engine::noteOff(int32_t pitch) {+void Engine::noteOff(int32_t pitch, float releaseVelocity) {{std::lock_guard<std::mutex> lk(liveMidiMx_);- liveMidi_.push(MidiEvent{false, pitch, 0.0f});+ liveMidi_.push(MidiEvent{false, pitch, std::clamp(releaseVelocity, 0.0f, 1.0f)});}if (pitch >= 0 && pitch < 128) liveHeld_[pitch >> 5].fetch_and(~(1u << (pitch & 31)), std::memory_order_relaxed);}@@ -288,10 +288,10 @@ void Engine::trackNoteOn(int32_t trackId, int32_t pitch, float velocity) {}if (pitch >= 0 && pitch < 128) liveHeld_[pitch >> 5].fetch_or(1u << (pitch & 31), std::memory_order_relaxed);}-void Engine::trackNoteOff(int32_t trackId, int32_t pitch) {+void Engine::trackNoteOff(int32_t trackId, int32_t pitch, float releaseVelocity) {{std::lock_guard<std::mutex> lk(remoteMidiMx_);- remoteMidi_.push(MidiEvent{false, pitch, 0.0f, trackId});+ remoteMidi_.push(MidiEvent{false, pitch, std::clamp(releaseVelocity, 0.0f, 1.0f), trackId});}if (pitch >= 0 && pitch < 128) liveHeld_[pitch >> 5].fetch_and(~(1u << (pitch & 31)), std::memory_order_relaxed);}diff --git a/src/native/nota.engine/src/engine/Engine_Render.cpp b/src/native/nota.engine/src/engine/Engine_Render.cppindex a2a77d3a..8aa8bb42 100644--- a/src/native/nota.engine/src/engine/Engine_Render.cpp+++ b/src/native/nota.engine/src/engine/Engine_Render.cpp@@ -103,21 +103,32 @@ inline bool midiEvLess(const MidiEv& a, const MidiEv& b) {inline bool pedalHolds(const Instrument& inst, int32_t pitch) {return pitch >= 0 && pitch < 128 && ((inst.pedalHeld[pitch >> 6].load(std::memory_order_relaxed) >> (pitch & 63)) & 1u);}+// A note-off the pedal held, sent now with the release velocity its key-up carried.+inline void sendHeldNoteOff(Instrument& inst, int32_t pitch) {+ const uint8_t rv = inst.pedalRelVel[pitch].exchange(0, std::memory_order_relaxed);+ if (rv > 0) inst.noteOffVelocity(pitch, static_cast<float>(rv) / 127.0f);+ else+ inst.noteOff(pitch);+}inline void sendNoteOn(Instrument& inst, int32_t pitch, float vel) {if (pedalHolds(inst, pitch)) {auto& h = inst.pedalHeld[pitch >> 6];h.store(h.load(std::memory_order_relaxed) & ~(uint64_t{1} << (pitch & 63)), std::memory_order_relaxed);- inst.noteOff(pitch);+ sendHeldNoteOff(inst, pitch);}inst.noteOn(pitch, vel);}-inline void sendNoteOff(Instrument& inst, int32_t pitch) {+inline void sendNoteOff(Instrument& inst, int32_t pitch, float releaseVel = 0.0f) {if (inst.pedalDown.load(std::memory_order_relaxed) && pitch >= 0 && pitch < 128 && !inst.handlesSustain()) {auto& h = inst.pedalHeld[pitch >> 6];h.store(h.load(std::memory_order_relaxed) | (uint64_t{1} << (pitch & 63)), std::memory_order_relaxed);+ const long rv = std::lround(std::clamp(releaseVel, 0.0f, 1.0f) * 127.0f);+ inst.pedalRelVel[pitch].store(static_cast<uint8_t>(releaseVel > 0.0f ? std::max(1L, rv) : 0L), std::memory_order_relaxed);return;}- inst.noteOff(pitch);+ if (releaseVel > 0.0f) inst.noteOffVelocity(pitch, releaseVel);+ else+ inst.noteOff(pitch);}inline void sendController(Instrument& inst, int32_t ctl, float value) {if (ctl == kCtlSustain && !inst.handlesSustain()) {@@ -125,7 +136,7 @@ inline void sendController(Instrument& inst, int32_t ctl, float value) {inst.pedalDown.store(down, std::memory_order_relaxed);if (!down) {for (int32_t p = 0; p < 128; ++p)- if (pedalHolds(inst, p)) inst.noteOff(p);+ if (pedalHolds(inst, p)) sendHeldNoteOff(inst, p);inst.pedalHeld[0].store(0, std::memory_order_relaxed);inst.pedalHeld[1].store(0, std::memory_order_relaxed);}@@ -212,7 +223,7 @@ void playEvents(Instrument& inst, float* dst, int32_t frames, const MidiEv* evs,if (nOff <= xOff) {if (evs[k].on) sendNoteOn(inst, evs[k].pitch, evs[k].vel);else- sendNoteOff(inst, evs[k].pitch);+ sendNoteOff(inst, evs[k].pitch, evs[k].vel);++k;} else {deliverExpr(inst, xev[x].pitch, xev[x].dim, xev[x].value);diff --git a/tests/Nota.SmokeTest/BrowserCategoryTests.cs b/tests/Nota.SmokeTest/BrowserCategoryTests.csindex ff92da48..e5f38628 100644--- a/tests/Nota.SmokeTest/BrowserCategoryTests.cs+++ b/tests/Nota.SmokeTest/BrowserCategoryTests.cs@@ -52,7 +52,7 @@ internal static class BrowserCategoryTests// Picks are per tab, and a pick keeps "Group by source"'s header.vm.SetCategoryFilter(1, "Reverb & delay");- yield return (vm.CategoryFilter(1) == "Reverb & delay" && vm.CategoryFilter(0) == "" && Devices(vm.Instruments).Count == 16,+ yield return (vm.CategoryFilter(1) == "Reverb & delay" && vm.CategoryFilter(0) == "" && Devices(vm.Instruments).Count == 17,"a pick narrows only its own tab");yield return (vm.Effects.Select(r => r.Name).SequenceEqual(new[] { "BUILT-IN", "Nota Chamber", "Nota Delay", "Nota Reverb" }),$"Reverb & delay lists Chamber, Delay, Reverb ({string.Join(", ", vm.Effects.Select(r => r.Name))})");diff --git a/tests/Nota.SmokeTest/DesignTokenCheck.Browser.cs b/tests/Nota.SmokeTest/DesignTokenCheck.Browser.csindex 395612fe..c2a3d438 100644--- a/tests/Nota.SmokeTest/DesignTokenCheck.Browser.cs+++ b/tests/Nota.SmokeTest/DesignTokenCheck.Browser.cs@@ -16,7 +16,7 @@ internal static partial class DesignTokenCheckvar types = new[] { BuiltinDeviceType.Instrument, BuiltinDeviceType.AudioEffect, BuiltinDeviceType.MidiEffect };var expected = new Dictionary<BuiltinDeviceType, int>{- [BuiltinDeviceType.Instrument] = 16, [BuiltinDeviceType.AudioEffect] = 27, [BuiltinDeviceType.MidiEffect] = 7, // + the MIDI Effect Rack (specs/040)+ [BuiltinDeviceType.Instrument] = 17, [BuiltinDeviceType.AudioEffect] = 27, [BuiltinDeviceType.MidiEffect] = 7, // + the MIDI Effect Rack (specs/040)};foreach (var type in types){diff --git a/tests/Nota.SmokeTest/LocalizationAllowList.txt b/tests/Nota.SmokeTest/LocalizationAllowList.txtindex 47c505f9..7f8679f2 100644--- a/tests/Nota.SmokeTest/LocalizationAllowList.txt+++ b/tests/Nota.SmokeTest/LocalizationAllowList.txt@@ -285,6 +285,7 @@ Nota.App/Controls/SynthViz.cs note off # data: device parameter, port and valueNota.App/Controls/SynthViz.cs release # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/Controls/SynthViz.cs resonance # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/Controls/SynthViz.cs sustain # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/Controls/TwinViews.cs $"{NotaNum.Pct((float)rt)} parallel" # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/Controls/UtilityViews.cs Stereo field # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/Controls/ValueBar.cs Value # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/Controls/ValueEntry.cs Scope # data: device parameter, port and value names and live readouts of their values (FR-004)@@ -1909,6 +1910,139 @@ Nota.App/DeviceCards/Instruments/SynthInstrumentCard.cs Triangle # data: deviceNota.App/DeviceCards/Instruments/SynthInstrumentCard.cs Vel → Vol # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Instruments/SynthInstrumentCard.cs Voices # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Instruments/SynthInstrumentCard.cs Volume # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs $"A {fmt(a)} · B {fmt(b)} · now {fmt(sounding)}" # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs $"Macro {k}" # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs $"Osc {n}" # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs $"Pattern {EditPat() + 1}" # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs $"Pattern {i}" # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs $"X {Bip(G(" # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs $"{PartNames[partIx]} part" # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs $"{Pat()?.Length ?? 16} steps" # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs $"{n} steps" # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs 1 bar # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs 2 bars # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs 4 bars # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs 8 bars # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs All # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Amount # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Amp env # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Arp # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs As played # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Attack # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Bend range # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Both # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Brute # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Chord # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Chorus # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Coarse # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Colour # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Curve # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Cutoff # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Damping # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Decay # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Delay # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Depth # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Detune # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Division # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Down # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Drift # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Drive # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Ensemble # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Env # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs FM 1 # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs FM cut # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Fade # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Feedback # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Filter # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Filter env # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Fine # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Flanger # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Gate # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Glide # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Glide only legato # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Global # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Hold # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Key # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs LFO 1 # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs LFO 1 × mod wheel # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs LFO 2 # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs LFO 3 # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Ladder # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Latch # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Layer # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Legato # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Level # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Loop # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Low # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Lower # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Macros # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Matrix # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Metal # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Mix # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Mod FX # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Mod env # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Mode # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Mono # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Morph # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Morphing poly # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Motion # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Multimode # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Noise # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs None # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Octave # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Octaves # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Osc # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Output # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Pad # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Pad X # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Pad Y # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Pad Z # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Pan # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Parts # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Phaser # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Ping-pong # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Plays # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Poly # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Random # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Rate # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Release # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Reso # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Resonance # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Response # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Retrig # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Reverb # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Route # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Saw # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Seq # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Sequencer # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Sequencer Swing # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Sine # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Single # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Size # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Smooth # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Split # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Spread # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Spread by # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Square # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Steps # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Stereo # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Sustain # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Swing # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Symmetry # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Sync # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Time # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs To filter # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Transpose # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Tri # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Unison # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Upper # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Velocity # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Vibrato # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Voice # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Voices # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Volume # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Wave # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Instruments/TwinInstrumentCard.cs Width # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Instruments/VoltInstrumentCard.cs Depth # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Instruments/VoltInstrumentCard.cs Fade # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Instruments/VoltInstrumentCard.cs Fine # data: device parameter, port and value names and live readouts of their values (FR-004)@@ -2209,6 +2343,7 @@ Nota.App/DeviceCards/Rack/RackCard.Chains.cs Nota Operator # data: device parameNota.App/DeviceCards/Rack/RackCard.Chains.cs Nota Pendulum # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Rack/RackCard.Chains.cs Nota Pentad # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Rack/RackCard.Chains.cs Nota Physical # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Rack/RackCard.Chains.cs Nota Twin # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Rack/RackCard.Chains.cs Nota Volt # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Rack/RackCard.Chains.cs Plug # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Rack/RackCard.Chains.cs Solo chain # data: device parameter, port and value names and live readouts of their values (FR-004)@@ -2271,6 +2406,7 @@ Nota.App/DeviceCards/Rack/RackCardView.Drum.cs Nota Pendulum # data: device paraNota.App/DeviceCards/Rack/RackCardView.Drum.cs Nota Pentad # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Rack/RackCardView.Drum.cs Nota Physical # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Rack/RackCardView.Drum.cs Nota Sampler # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Rack/RackCardView.Drum.cs Nota Twin # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Rack/RackCardView.Drum.cs Nota Volt # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Rack/RackCardView.Drum.cs Off # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Rack/RackCardView.Drum.cs Pad Mute # data: device parameter, port and value names and live readouts of their values (FR-004)@@ -2327,6 +2463,7 @@ Nota.App/DeviceCards/Rack/RackCardView.cs Nota Reverb # data: device parameter,Nota.App/DeviceCards/Rack/RackCardView.cs Nota Sampler # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Rack/RackCardView.cs Nota Shutter # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Rack/RackCardView.cs Nota Strata # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.App/DeviceCards/Rack/RackCardView.cs Nota Twin # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Rack/RackCardView.cs Nota Utility # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Rack/RackCardView.cs Nota Valve # data: device parameter, port and value names and live readouts of their values (FR-004)Nota.App/DeviceCards/Rack/RackCardView.cs Nota Vintage # data: device parameter, port and value names and live readouts of their values (FR-004)@@ -2620,6 +2757,7 @@ Nota.Application/Palette/BuiltinDeviceCatalog.cs Nota Sampler # data: search keyNota.Application/Palette/BuiltinDeviceCatalog.cs Nota Scale # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/BuiltinDeviceCatalog.cs Nota Shutter # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/BuiltinDeviceCatalog.cs Nota Strata # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)+Nota.Application/Palette/BuiltinDeviceCatalog.cs Nota Twin # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/BuiltinDeviceCatalog.cs Nota Utility # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/BuiltinDeviceCatalog.cs Nota Valve # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/BuiltinDeviceCatalog.cs Nota Velocity # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)@@ -2683,6 +2821,7 @@ Nota.Application/Palette/BuiltinDeviceCatalog.cs layer split instrumentrack # daNota.Application/Palette/BuiltinDeviceCatalog.cs lofi gritty # data: search keyword or alias of the palette and the browser, not shownNota.Application/Palette/BuiltinDeviceCatalog.cs lofi hiphop # data: search keyword or alias of the palette and the browser, not shownNota.Application/Palette/BuiltinDeviceCatalog.cs loop overdub # data: search keyword or alias of the palette and the browser, not shown+Nota.Application/Palette/BuiltinDeviceCatalog.cs lush aggressive warm evolving # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/BuiltinDeviceCatalog.cs lush vintage warm # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/BuiltinDeviceCatalog.cs master bus # data: search keyword or alias of the palette and the browser, not shownNota.Application/Palette/BuiltinDeviceCatalog.cs master bus drums # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)@@ -2700,10 +2839,12 @@ Nota.Application/Palette/BuiltinDeviceCatalog.cs oscilloscope spectrum meter # dNota.Application/Palette/BuiltinDeviceCatalog.cs ott upward multibandcompressor # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/BuiltinDeviceCatalog.cs pad bass lead keys pluck # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/BuiltinDeviceCatalog.cs pad keys lead brass # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)+Nota.Application/Palette/BuiltinDeviceCatalog.cs pad keys lead brass bass # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/BuiltinDeviceCatalog.cs pad lead texture # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/BuiltinDeviceCatalog.cs pad texture # data: search keyword or alias of the palette and the browser, not shownNota.Application/Palette/BuiltinDeviceCatalog.cs panner tremolo # data: search keyword or alias of the palette and the browser, not shownNota.Application/Palette/BuiltinDeviceCatalog.cs pluck bell keys strings perc # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)+Nota.Application/Palette/BuiltinDeviceCatalog.cs polysynth poly morph morphing analog two-filter steiner ladder split layer expressive mpe # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/BuiltinDeviceCatalog.cs prophet poly # data: search keyword or alias of the palette and the browser, not shownNota.Application/Palette/BuiltinDeviceCatalog.cs repair transient # data: search keyword or alias of the palette and the browser, not shownNota.Application/Palette/BuiltinDeviceCatalog.cs seq pluck # data: search keyword or alias of the palette and the browser, not shown@@ -2713,6 +2854,7 @@ Nota.Application/Palette/BuiltinDeviceCatalog.cs stutter repeat buffer # data: sNota.Application/Palette/BuiltinDeviceCatalog.cs synth drums bass # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/BuiltinDeviceCatalog.cs synth keys # data: search keyword or alias of the palette and the browser, not shownNota.Application/Palette/BuiltinDeviceCatalog.cs synth keys guitar vocals # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)+Nota.Application/Palette/BuiltinDeviceCatalog.cs synthwave cinematic # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/BuiltinDeviceCatalog.cs synthwave techno # data: search keyword or alias of the palette and the browser, not shownNota.Application/Palette/BuiltinDeviceCatalog.cs synthwave techno acid house # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/BuiltinDeviceCatalog.cs synthwave trance # data: search keyword or alias of the palette and the browser, not shown@@ -2862,6 +3004,7 @@ Nota.Application/Palette/DeviceCategories.cs Nota Prism # data: search keywords,Nota.Application/Palette/DeviceCategories.cs Nota Random # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/DeviceCategories.cs Nota Shutter # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/DeviceCategories.cs Nota Strata # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)+Nota.Application/Palette/DeviceCategories.cs Nota Twin # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/DeviceCategories.cs Nota Velocity # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/DeviceCategories.cs Nota Vintage # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/DeviceCategories.cs Nota Vocoder # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)@@ -2912,6 +3055,45 @@ Nota.Application/Palette/SemanticVocabulary.cs tape stop # data: search keywordNota.Application/Ports/ISampleStore.cs Downloaded # data: folder name on diskNota.Application/Samples/MusicalKey.cs major # data: key name — musical notation (spec 068 data-model)Nota.Application/Samples/MusicalKey.cs minor # data: key name — musical notation (spec 068 data-model)+Nota.Application/Twin/TwinMatrix.cs Amp env # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Bend # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Filter env # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Key # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs LFO 1 # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs LFO 2 # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs LFO 3 # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Macro 1 # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Macro 2 # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Macro 3 # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Macro 4 # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Macro 5 # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Macro 6 # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Macro 7 # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Macro 8 # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Mod env # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Mod wheel # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Morph # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs None # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Osc 1 pitch # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Osc 2 pitch # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Pad X # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Pad Y # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Pad Z # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Pitch # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Pitch wheel # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Pressure # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Random # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Release velocity # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Seq gate # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Seq step # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Slide # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Velocity # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinMatrix.cs Vibrato # data: device parameter, port and value names and live readouts of their values (FR-004)+Nota.Application/Twin/TwinPatterns.cs $"gate '{parts[2]}'" # data: instrument tool text for MCP+Nota.Application/Twin/TwinPatterns.cs $"note '{t}'" # data: instrument tool text for MCP+Nota.Application/Twin/TwinPatterns.cs $"row {i + 1}: {err}" # data: instrument tool text for MCP+Nota.Application/Twin/TwinPatterns.cs $"velocity '{parts[1]}'" # data: instrument tool text for MCP+Nota.Application/Twin/TwinPatterns.cs $"{rows.Count} rows — a pattern has 1..{Steps}" # data: instrument tool text for MCPNota.Presentation/PaletteProviders.cs Plug-in # data: identifier compared in codeNota.Presentation/PaletteProviders.cs group folder # data: search keyword or alias of the palette and the browser, not shownNota.Presentation/PaletteProviders.cs midi instrument # data: search keyword or alias of the palette and the browser, not showndiff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 912a184f..7518df88 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -737,6 +737,14 @@ if (args.Length >= 1 && args[0] == "--keys")Console.WriteLine(failures == 0 ? "KEYS PASSED" : $"KEYS FAILED ({failures})");return failures == 0 ? 0 : 1;}+// Nota Twin alone (fast iteration): `--twin`. Also part of the full run.+if (args.Length >= 1 && args[0] == "--twin")+{+ Console.WriteLine("-- nota twin --");+ foreach (var (ok, label) in TwinTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "TWIN PASSED" : $"TWIN FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}// Nota Vocoder alone (fast iteration): `--vocoder`. Also part of the full run.if (args.Length >= 1 && args[0] == "--vocoder"){@@ -15502,6 +15510,8 @@ Console.WriteLine("-- meter --");foreach (var (ok, label) in MeterTests.Run()) Check(ok, label);Console.WriteLine("-- nota keys --");foreach (var (ok, label) in KeysTests.Run()) Check(ok, label);+Console.WriteLine("-- nota twin --");+foreach (var (ok, label) in TwinTests.Run()) Check(ok, label);Console.WriteLine("-- nota vocoder --");foreach (var (ok, label) in VocoderTests.Run()) Check(ok, label);Console.WriteLine("-- instrument on/off --");diff --git a/tests/Nota.SmokeTest/TwinTests.cs b/tests/Nota.SmokeTest/TwinTests.csnew file mode 100644index 00000000..8fb9f1cf--- /dev/null+++ b/tests/Nota.SmokeTest/TwinTests.cs@@ -0,0 +1,1495 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Twin (instrument kind 18, specs/055): identity, the A/B param table (both parts, both+// sides, the matrix), project state — round trip, an older shorter blob, a foreign blob — clone+// and replace; the voice (US1): Init level against Volt, pitch, the 12-voice pool and stealing,+// Unison and Mono, the voice cap, both filters' modes and self-oscillation, bounded extremes,+// and block-size independence (a clip renders the same at any block size); the factory presets;+// the morph (US2): exact endpoints, equal sides are silent, a sweep adds no jump of its own;+// expression (US3): per-note pressure and bend move only their note, channel pressure moves all,+// the pad's three axes, MPE support; the matrix (US4): the app's tables match the engine's, a+// zero-depth route is silent, depth morphs with the sides, a per-note source on the Morph moves+// only its note, adding into a full matrix fails, route edits undo in one step; the effects+// (US5): the section switch bypasses exactly, each effect is heard, a synced delay follows the+// tempo, a reverb tail rings past the note; the sequencer (US8): edits undo in one step, steps+// land on the grid at any tempo and block size, a stop releases, step record, transpose, the+// arpeggiator, patterns in the state and "To clip"; Split / Layer (US9): key routing, the voice+// share, both parts in Layer, a layout change releases.++using System.IO;+using Nota.Application;+using Nota.Application.Editing;+using Nota.Application.Twin;+using Nota.Infrastructure;++namespace Nota.SmokeTest;++internal static class TwinTests+{+ private const int Sr = 48000;+ private const int Params = 965; // globals 21 + 2 parts × (part 144 + 2 sides × 164)++ private static int Pi(IAudioEngine e, int t, string id)+ {+ int n = e.PluginParamCount(t, -1);+ for (int i = 0; i < n; i++) if (e.PluginParamId(t, -1, i) == id) return i;+ return -1;+ }+ private static float G(IAudioEngine e, int t, string id) => e.PluginParamGet(t, -1, Pi(e, t, id));+ private static void P(IAudioEngine e, int t, string id, float v) => e.PluginParamSet(t, -1, Pi(e, t, id), v);++ private static double Rms(float[] st, int from = 0)+ {+ double s = 0;+ for (int i = from * 2; i < st.Length; i++) s += st[i] * (double)st[i];+ return Math.Sqrt(s / Math.Max(1, st.Length - from * 2));+ }+ private static double Db(double x) => 20 * Math.Log10(Math.Max(x, 1e-12));+ private static double Peak(float[] st) { double p = 0; foreach (var v in st) p = Math.Max(p, Math.Abs(v)); return p; }+ // Energy at one frequency (Goertzel), mono sum.+ private static double At(float[] st, double hz, int from = 0)+ {+ double w = 2 * Math.PI * hz / Sr, c = 2 * Math.Cos(w), s1 = 0, s2 = 0;+ for (int i = from * 2; i < st.Length; i += 2) { double s0 = (st[i] + st[i + 1]) * 0.5 + c * s1 - s2; s2 = s1; s1 = s0; }+ return Math.Sqrt(Math.Max(0, s1 * s1 + s2 * s2 - c * s1 * s2));+ }++ // A fresh engine with one instrument track (Twin by default), notes held live, `frames` rendered.+ private static (float[] Out, int Voices) Hold(int[] notes, int frames, Action<NotaEngine, int>? setup = null, bool volt = false)+ {+ using var e = new NotaEngine();+ int t = volt ? e.AddVoltSynthTrack() : e.AddTwinTrack();+ setup?.Invoke(e, t);+ Render(e, 512);+ foreach (var n in notes) e.TrackNoteOn(t, n, 0.8f);+ var o = Render(e, frames);+ return (o, e.InstrumentVoiceCount(t));+ }++ // A clip-driven render (transport rolling) at a given block size, after an optional setup.+ private static float[] Play(int block, int frames, Action<NotaEngine, int>? setup = null)+ {+ using var e = new NotaEngine();+ e.SetBpm(120);+ int t = e.AddTwinTrack();+ if (setup is not null) setup(e, t);+ else+ {+ P(e, t, "lo.a.o2level", 0.7f); P(e, t, "lo.a.o1bal", 0.5f); P(e, t, "lo.a.route", 0.4f); P(e, t, "lo.a.drift", 0.8f);+ e.AddMidiClip(t, 0.0, 8.0);+ e.SetClipNotes(t, 0, new[] { new NotaNote(48, 0.0, 1.5, 0.8f), new NotaNote(55, 0.25, 1.0, 0.6f), new NotaNote(64, 1.0, 2.0, 0.9f), new NotaNote(43, 2.0, 1.0, 0.7f) });+ }+ var outv = new float[frames * 2];+ var tmp = new float[block * 2];+ e.Seek(0); e.Play();+ for (int done = 0; done < frames;) { int m = Math.Min(block, frames - done); e.RenderOffline(tmp, m, Sr); Array.Copy(tmp, 0, outv, done * 2, m * 2); done += m; }+ e.StopTransport();+ return outv;+ }++ // A two-sided patch: A dark and slow, B bright and plucked, differing in stepped params too.+ private static void TwoSided(NotaEngine e, int t)+ {+ foreach (var (id, a, b) in new[] { ("ldcut", 0.35f, 0.8f), ("o1wave", 0.5f, 1f), ("o2level", 0f, 0.6f), ("o2coarse", 0.5f, 0.75f),+ ("aenva", 0.6f, 0.1f), ("aenvs", 1f, 0.3f), ("ldres", 0.1f, 0.5f), ("ldslope", 1f, 0f), ("sync", 0f, 1f), ("mmmode", 0f, 0.7f) })+ {+ P(e, t, "lo.a." + id, a);+ P(e, t, "lo.b." + id, b);+ }+ }+ // Copy one side of the Lower part onto the other.+ private static void CopySide(NotaEngine e, int t, char from, char to)+ {+ int n = e.PluginParamCount(t, -1);+ for (int i = 0; i < n; i++)+ {+ string id = e.PluginParamId(t, -1, i);+ if (id.StartsWith($"lo.{to}.")) P(e, t, id, G(e, t, $"lo.{from}." + id[5..]));+ }+ }+ private static float[] Chord(Action<NotaEngine, int> setup, int frames = Sr * 2, Action<NotaEngine, int, int>? perBlock = null)+ {+ using var e = new NotaEngine();+ e.SetBpm(120);+ int t = e.AddTwinTrack();+ setup(e, t);+ e.AddMidiClip(t, 0.0, 8.0);+ e.SetClipNotes(t, 0, new[] { 48, 55, 60, 64 }.Select(n => new NotaNote(n, 0, 3.5, 0.8f)).ToArray());+ var outv = new float[frames * 2];+ var tmp = new float[128 * 2];+ e.Seek(0); e.Play();+ for (int done = 0, blk = 0; done < frames; blk++)+ {+ perBlock?.Invoke(e, t, blk);+ int m = Math.Min(128, frames - done);+ e.RenderOffline(tmp, m, Sr);+ Array.Copy(tmp, 0, outv, done * 2, m * 2);+ done += m;+ }+ return outv;+ }+ private static double MaxStep(float[] st, int from, int to)+ {+ double d = 0;+ for (int i = Math.Max(1, from); i < to; i++) d = Math.Max(d, Math.Max(Math.Abs(st[2 * i] - st[2 * i - 2]), Math.Abs(st[2 * i + 1] - st[2 * i - 1])));+ return d;+ }++ private static float[] Render(NotaEngine e, int frames, int block = 512)+ {+ var all = new float[frames * 2];+ var b = new float[block * 2];+ for (int done = 0; done < frames;)+ {+ int m = Math.Min(block, frames - done);+ e.RenderOffline(b, m, Sr);+ Array.Copy(b, 0, all, done * 2, m * 2);+ done += m;+ }+ return all;+ }++ public static IEnumerable<(bool, string)> Run()+ {+ using var e = new NotaEngine();+ int t = e.AddTwinTrack();+ yield return (t > 0 && e.TrackInstrumentKind(t) == 18, "AddTwinTrack adds a kind 18 instrument");+ yield return (e.DeviceName(t, -1) == "Nota Twin", $"instrument is Nota Twin (got '{e.DeviceName(t, -1)}')");+ yield return (InstrumentView.Index(e, t) >= 0 && !InstrumentView.IsMini(e, t), "Nota Twin has an S / L view param and opens as L");++ int n = e.PluginParamCount(t, -1);+ yield return (n == Params, $"Nota Twin exposes {Params} params (got {n})");+ var ids = new HashSet<string>();+ bool named = true;+ for (int i = 0; i < n; i++)+ {+ ids.Add(e.PluginParamId(t, -1, i));+ named &= !string.IsNullOrEmpty(e.PluginParamName(t, -1, i));+ }+ yield return (ids.Count == n && !ids.Contains("") && named, "twin param ids are unique + non-empty, every param has a name");++ // Layout: globals, then per part its side-less block, side A, side B; Upper B's last route depth ends it.+ bool layout = Pi(e, t, "mode") == 0 && Pi(e, t, "lo.morph") == 21 && Pi(e, t, "up.b.m64amt") == n - 1+ && Pi(e, t, "lo.b.ldcut") - Pi(e, t, "lo.a.ldcut") == 164+ && Pi(e, t, "up.a.ldcut") - Pi(e, t, "lo.a.ldcut") == 144 + 2 * 164;+ yield return (layout, "twin params follow the [globals][part][A][B] × 2 layout");+ yield return (e.PluginParamName(t, -1, Pi(e, t, "up.b.ldcut")) == "Upper B · Ladder Cutoff",+ $"twin names carry part and side (got '{e.PluginParamName(t, -1, Pi(e, t, "up.b.ldcut"))}')");+ yield return (Math.Abs(G(e, t, "lo.a.ldcut") - G(e, t, "lo.b.ldcut")) < 1e-6 && Math.Abs(G(e, t, "lo.a.m7amt") - 0.5f) < 1e-6+ && e.PluginParamText(t, -1, Pi(e, t, "lo.m1.src")) == "Pressure" && e.PluginParamText(t, -1, Pi(e, t, "lo.m1.dst")) == "Ladder Cutoff"+ && e.PluginParamText(t, -1, Pi(e, t, "lo.m5.dst")) == "Morph" && e.PluginParamText(t, -1, Pi(e, t, "lo.m7.src")) == "None",+ "twin Init: both sides equal; slots 1–6 hold the default expression routes, 7 on are empty");++ // State round trip onto another track.+ P(e, t, "lo.b.ldcut", 0.25f); P(e, t, "up.a.o2wave", 0.9f); P(e, t, "lo.m3.src", 4f / 63f); P(e, t, "lo.morph", 0.4f);+ var st = e.GetPluginState(t, -1);+ int t2 = e.AddTwinTrack();+ e.SetPluginState(t2, -1, st);+ bool same = true;+ for (int i = 0; i < n; i++) same &= e.PluginParamGet(t2, -1, i) == e.PluginParamGet(t, -1, i);+ yield return (st.Length > 12 + 4 * n && same, $"twin state ({st.Length} bytes: params and patterns) restores every param on another track");++ // An older, shorter blob: its params load, the rest keep their defaults (FR-052).+ int t3 = e.AddTwinTrack();+ var shortBlob = new byte[8 + 4 * 30 + 4];+ Array.Copy(st, 0, shortBlob, 0, 4);+ BitConverter.GetBytes(30u).CopyTo(shortBlob, 4);+ Array.Copy(st, 8, shortBlob, 8, 4 * 30);+ e.SetPluginState(t3, -1, shortBlob);+ yield return (Math.Abs(G(e, t3, "lo.morph") - 0.4f) < 1e-6 && Math.Abs(G(e, t3, "lo.b.ldcut") - G(e, t3, "lo.a.ldcut")) < 1e-6,+ "a shorter twin blob loads its params and leaves the rest at defaults");++ // A blob that isn't Twin's is ignored.+ var foreign = (byte[])st.Clone();+ foreign[0] ^= 0xFF;+ int t4 = e.AddTwinTrack();+ e.SetPluginState(t4, -1, foreign);+ yield return (Math.Abs(G(e, t4, "lo.morph")) < 1e-6, "a twin blob with a foreign magic is ignored");++ int dup = e.DuplicateTrack(t);+ yield return (dup > 0 && Math.Abs(G(e, dup, "lo.b.ldcut") - 0.25f) < 1e-6 && Math.Abs(G(e, dup, "up.a.o2wave") - 0.9f) < 1e-6,+ "duplicate track clones the twin patch");++ int other = e.AddVoltSynthTrack();+ yield return (e.SetTrackBuiltinInstrument(other, 18) && e.TrackInstrumentKind(other) == 18, "replace swaps an instrument for Nota Twin");++ var silent = Render(e, 4096);+ yield return (silent.All(float.IsFinite), "the twin shell renders finite");++ // ---- the voice (US1) ----------------------------------------------------------------+ int[] chord = { 48, 55, 60, 64 };+ var (tw, _) = Hold(chord, Sr * 2);+ var (vo, _) = Hold(chord, Sr * 2, volt: true);+ double d = Db(Rms(tw, Sr / 2)) - Db(Rms(vo, Sr / 2));+ yield return (tw.All(float.IsFinite) && Math.Abs(d) <= 1.5, $"twin Init chord sits within ±1.5 dB of Volt's Init ({d:+0.00;-0.00} dB)");++ var (a3, v1) = Hold(new[] { 57 }, Sr);+ yield return (v1 == 1 && At(a3, 220, 4800) > 10 * At(a3, 233.08, 4800), "twin plays A3 at 220 Hz on one voice");++ var notes13 = Enumerable.Range(0, 13).Select(k => 40 + 3 * k).ToArray();+ var (o13, v13) = Hold(notes13, Sr / 2);+ yield return (v13 == 12 && o13.All(float.IsFinite), $"13 held notes sound on 12 voices ({v13})");+ var (o4, v4) = Hold(notes13, Sr / 2, (e2, t5) => P(e2, t5, "voices", 0f));+ yield return (v4 == 4, $"the voice cap holds the pool to 4 ({v4})");+ var (_, vu) = Hold(new[] { 48 }, Sr / 2, (e2, t5) => P(e2, t5, "lo.voicemode", 1f));+ yield return (vu == 12, $"Unison stacks every voice on one key ({vu})");+ var (_, vm) = Hold(new[] { 48, 60, 67 }, Sr / 2, (e2, t5) => P(e2, t5, "lo.voicemode", 1f / 3f));+ yield return (vm == 1, $"Mono plays one voice for a held chord ({vm})");++ var (lp, _) = Hold(new[] { 48 }, Sr, (e2, t5) => { P(e2, t5, "lo.a.o1bal", 0f); P(e2, t5, "lo.a.mmcut", 0.55f); P(e2, t5, "lo.a.mmmode", 0f); });+ var (hp, _) = Hold(new[] { 48 }, Sr, (e2, t5) => { P(e2, t5, "lo.a.o1bal", 0f); P(e2, t5, "lo.a.mmcut", 0.55f); P(e2, t5, "lo.a.mmmode", 0.667f); });+ yield return (At(lp, 130.81, 4800) > 10 * At(lp, 4186, 4800) && At(hp, 4186, 4800) > 3 * At(lp, 4186, 4800) && At(hp, 130.81, 4800) < 0.1 * At(lp, 130.81, 4800),+ "the multimode filter is a low-pass at mode 0 and a high-pass at 2/3");++ var (ls, _) = Hold(new[] { 60 }, Sr, (e2, t5) => { P(e2, t5, "lo.a.o1level", 0f); P(e2, t5, "lo.a.ldres", 1f); P(e2, t5, "lo.a.ldcut", 0.5f); P(e2, t5, "lo.a.ldenv", 0.5f); });+ var (ms, _) = Hold(new[] { 60 }, Sr, (e2, t5) => { P(e2, t5, "lo.a.o1level", 0f); P(e2, t5, "lo.a.o1bal", 0f); P(e2, t5, "lo.a.mmres", 1f); P(e2, t5, "lo.a.mmcut", 0.5f); });+ yield return (Db(Rms(ls, Sr / 2)) > -60 && Db(Rms(ms, Sr / 2)) > -60,+ $"both filters self-oscillate at full resonance with no source (ladder {Db(Rms(ls, Sr / 2)):0} dB, multimode {Db(Rms(ms, Sr / 2)):0} dB)");++ var (ex, _) = Hold(new[] { 36, 60, 84, 96 }, Sr * 2, (e2, t5) =>+ {+ foreach (var id in new[] { "lo.a.brute", "lo.a.mmres", "lo.a.ldres", "lo.a.drive", "lo.a.o2level", "lo.a.noiselevel", "lo.a.fm21", "lo.a.fmfilt", "lo.a.o1metal" }) P(e2, t5, id, 1f);+ P(e2, t5, "lo.a.sync", 1f); P(e2, t5, "lo.a.route", 0f); P(e2, t5, "lo.a.o1bal", 0.5f); P(e2, t5, "lo.a.o1wave", 0f);+ });+ yield return (ex.All(float.IsFinite) && Peak(ex) < 2.0, $"maximum Brute, resonance, drive, FM, sync and Metal stay finite and bounded (peak {Db(Peak(ex)):0.0} dB)");++ var pa = Play(512, Sr * 3);+ var pb = Play(77, Sr * 3);+ double md = 0;+ for (int i = 0; i < pa.Length; i++) md = Math.Max(md, Math.Abs(pa[i] - pb[i]));+ yield return (Rms(pa) > 1e-3 && md == 0, $"a twin clip renders bit-identically at blocks of 512 and 77 (max diff {md:G3})");++ static double Diff(float[] x, float[] y) { double d = 0; for (int i = 0; i < x.Length; i++) d = Math.Max(d, Math.Abs(x[i] - y[i])); return d; }++ // ---- factory presets ------------------------------------------------------------------+ var cat = new FactoryPresetCatalog();+ var mine = cat.All().Where(p => p.IsInstrument && p.BuiltinKind == 18).ToList();+ var folders = mine.Select(p => p.Category).Distinct().ToList();+ yield return (mine.Count >= 110 && folders.Count >= 11, $"Nota Twin ships ≥ 110 factory presets in ≥ 11 folders ({mine.Count} in {string.Join(", ", folders)})");+ var bad = mine.SelectMany(p => cat.Document(p.Id)!.NamedParams!.Keys.Where(k => !ids.Contains(k)).Select(k => $"{p.DisplayName}:{k}")).ToList();+ yield return (bad.Count == 0, $"every Twin preset param id exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");+ int tp = e.AddTwinTrack();+ int fails = 0;+ double slowest = 0;+ foreach (var p in mine)+ {+ var clock = System.Diagnostics.Stopwatch.StartNew();+ if (cat.ApplyInPlace(e, p.Id, tp, -1).Length != 0) fails++;+ slowest = Math.Max(slowest, clock.Elapsed.TotalMilliseconds);+ }+ yield return (fails == 0 && slowest < 50, $"every Twin preset applies in place, the slowest in {slowest:0.0} ms (< 50; {fails} failed)");+ // SC-011: Split / Layer presets, and one plays its parts where it says.+ var two = mine.Where(p => cat.Document(p.Id)!.NamedParams!.TryGetValue("mode", out var md) && md > 0.25f).ToList();+ var bassPad = two.FirstOrDefault(p => p.DisplayName == "Bass + Pad Split");+ bool splits = false;+ if (bassPad.Id is not null)+ {+ using var se = new NotaEngine();+ int bt = se.AddTwinTrack();+ cat.ApplyInPlace(se, bassPad.Id, bt, -1);+ se.TrackNoteOn(bt, 36, 0.8f); se.TrackNoteOn(bt, 60, 0.8f); se.TrackNoteOn(bt, 64, 0.8f);+ Render(se, 2048);+ var sc = new float[32];+ se.InstrumentScope(bt, sc);+ splits = sc[4] == 1 && sc[5] == 2;+ }+ yield return (two.Count >= 6 && splits, $"≥ 6 factory presets split or layer the parts ({two.Count}); Bass + Pad Split plays C1 on Lower and C4 / E4 on Upper");++ // The preset name and its "modified" mark (specs/048), and a user preset of the sound.+ const PresetSurface Inst = PresetSurface.Instrument;+ var first = mine[0];+ string pw = PresetEdit.Apply(e, tp, Inst, -1, first.Id, first.DisplayName, () => cat.ApplyInPlace(e, first.Id, tp, -1));+ bool tagged = pw == "" && PresetEdit.Name(e, tp, Inst, -1) == first.DisplayName && e.DevicePresetModified(tp, Inst, -1) == 0;+ float cut0 = G(e, tp, "lo.b.ldcut");+ P(e, tp, "lo.b.ldcut", cut0 > 0.5f ? 0.2f : 0.8f);+ bool marked = e.DevicePresetModified(tp, Inst, -1) == 1;+ P(e, tp, "lo.b.ldcut", cut0);+ yield return (tagged && marked && e.DevicePresetModified(tp, Inst, -1) == 0,+ "a Twin preset names the card; moving a side-B knob marks it modified, moving it back clears the mark");+ P(e, tp, "lo.b.o2wave", 0.33f); P(e, tp, "lo.m9.src", 3 / 63f); P(e, tp, "lo.m9.dst", 1 / 255f); P(e, tp, "lo.a.m9amt", 0.8f);+ var doc = PresetService.Capture(e, tp, -1, "Mine")!;+ int tq = e.AddTwinTrack();+ PresetService.ApplyInPlace(doc, e, tq, -1);+ int pcount = e.PluginParamCount(tp, -1), diffs = 0;+ for (int i = 0; i < pcount; i++) if (e.PluginParamId(tp, -1, i) != "view" && e.PluginParamGet(tp, -1, i) != e.PluginParamGet(tq, -1, i)) diffs++;+ yield return (doc.NamedParams!.Count >= pcount - 1 && diffs == 0, $"a user preset keeps both sides and the matrix ({doc.NamedParams.Count} params; {diffs} differ after applying it)");+ var off = new List<string>();+ int twoSided = 0;+ foreach (var p in mine)+ {+ float[]? sideA = null;+ foreach (float morph in new[] { 0f, 1f })+ {+ var b = Play(512, Sr * 2, (e2, t5) => { cat.ApplyInPlace(e2, p.Id, t5, -1); P(e2, t5, "lo.morph", morph); P(e2, t5, "up.morph", morph); e2.AddMidiClip(t5, 0.0, 8.0);+ e2.SetClipNotes(t5, 0, new[] { 48, 52, 55, 60, 64, 67, 71, 72 }.Select(n => new NotaNote(n, 0, 3, 100f / 127f)).ToArray()); });+ double r = Rms(b), pk = Peak(b);+ if (!b.All(float.IsFinite) || r < 0.003 || pk >= 1.0) off.Add($"{p.DisplayName} {(morph == 0 ? "A" : "B")} ({Db(r):0} dB / peak {Db(pk):0.0} dB)");+ if (sideA is null) sideA = b;+ else if (Diff(sideA, b) > 0.01) twoSided++;+ }+ }+ yield return (off.Count == 0, $"every Twin preset sounds an 8-note chord at velocity 100 on both sides, finite, peak under 0 dBFS{(off.Count > 0 ? " — " + string.Join(", ", off) : "")}");+ yield return (twoSided == mine.Count, $"every Twin preset's side B differs from its side A ({twoSided}/{mine.Count})");++ // ---- the morph (US2) --------------------------------------------------------------------+ var atB = Chord((e2, t5) => { TwoSided(e2, t5); P(e2, t5, "lo.morph", 1f); });+ var bOnly = Chord((e2, t5) => { TwoSided(e2, t5); CopySide(e2, t5, 'b', 'a'); P(e2, t5, "lo.morph", 0f); });+ var atA = Chord((e2, t5) => { TwoSided(e2, t5); P(e2, t5, "lo.morph", 0f); });+ var aHalf = Chord((e2, t5) => { TwoSided(e2, t5); CopySide(e2, t5, 'a', 'b'); P(e2, t5, "lo.morph", 0.5f); });+ yield return (Rms(atB) > 1e-3 && Diff(atB, bOnly) == 0, $"Morph 1 renders exactly side B alone (max diff {Diff(atB, bOnly):G3})");+ yield return (Rms(atA) > 1e-3 && Diff(atA, aHalf) == 0, $"with both sides equal the morph changes nothing (max diff {Diff(atA, aHalf):G3})");+ yield return (Diff(atA, atB) > 0.01, "sides A and B sound different");+ int beat = Sr / 2;+ var sweep = Chord(TwoSided, perBlock: (e2, t5, blk) => P(e2, t5, "lo.morph", Math.Clamp((blk * 128 - Sr / 2) / (float)beat, 0f, 1f)));+ double own = Math.Max(MaxStep(atA, Sr / 2, Sr), MaxStep(atB, Sr / 2, Sr)), sw = MaxStep(sweep, Sr / 2, Sr);+ yield return (sweep.All(float.IsFinite) && sw <= own * 1.25, $"a one-beat Morph sweep adds no jump of its own (largest step {sw:0.000} vs the sides' {own:0.000})");++ // Side edits: A → B, then undo, then swap — each one undo step.+ using (var se = new NotaEngine())+ {+ int tt = se.AddTwinTrack();+ TwoSided(se, tt);+ se.ClearUndoHistory();+ float b0 = G(se, tt, "lo.b.ldcut"), a0 = G(se, tt, "lo.a.ldcut");+ int wrote = Nota.Application.Twin.TwinSides.Apply(se, tt, Nota.Application.Twin.TwinSides.Edit.CopyAToB);+ bool copied = wrote == 164 && G(se, tt, "lo.b.ldcut") == a0 && G(se, tt, "lo.b.sync") == G(se, tt, "lo.a.sync");+ bool canUndo = se.CanUndo, u = se.Undo();+ bool undone = u && G(se, tt, "lo.b.ldcut") == b0 && G(se, tt, "lo.b.o1wave") == 1f && !se.CanUndo;+ yield return (copied && canUndo && undone, $"A → B copies all 164 side params in one undo step (wrote {wrote})");+ Nota.Application.Twin.TwinSides.Apply(se, tt, Nota.Application.Twin.TwinSides.Edit.Swap);+ bool swapped = G(se, tt, "lo.a.ldcut") == b0 && G(se, tt, "lo.b.ldcut") == a0;+ yield return (swapped && se.Undo() && G(se, tt, "lo.a.ldcut") == a0 && !se.CanUndo, "Swap exchanges the sides in one undo step");+ }++ // ---- expression (US3) ---------------------------------------------------------------------+ yield return (e.TrackInstrumentSupportsMpe(t), "Nota Twin reports MPE support");+ int[] six = { 48, 52, 55, 58, 62, 65 }; // no note an octave of another+ double[] fund = six.Select(n => 440 * Math.Pow(2, (n - 69) / 12.0)).ToArray();+ float[] Expr(Action<NotaEngine, int>? after)+ {+ using var xe = new NotaEngine();+ int xt = xe.AddTwinTrack();+ P(xe, xt, "lo.a.ldcut", 0.4f); P(xe, xt, "lo.a.drift", 0f);+ Render(xe, 512);+ foreach (var n in six) xe.TrackNoteOn(xt, n, 0.8f);+ after?.Invoke(xe, xt);+ return Render(xe, Sr);+ }+ var plain = Expr(null);+ var pressed = Expr((xe, xt) => xe.TrackNoteExpression(xt, 55, NoteExpressionDim.Pressure, 1f));+ double worst = 0;+ for (int k = 0; k < six.Length; k++)+ if (six[k] != 55) worst = Math.Max(worst, Math.Abs(Db(At(pressed, fund[k], 4800)) - Db(At(plain, fund[k], 4800))));+ double self = Math.Abs(Db(At(pressed, 196 * 3, 4800)) - Db(At(plain, 196 * 3, 4800)));+ yield return (worst <= 0.5 && self > 1, $"pressure on one note of a 6-note chord opens only that note (others within {worst:0.00} dB, its 3rd harmonic {self:+0.0;-0.0} dB)");++ var bent = Expr((xe, xt) => xe.TrackNoteExpression(xt, 55, NoteExpressionDim.Bend, 2f));+ double bworst = 0;+ for (int k = 0; k < six.Length; k++)+ if (six[k] != 55) bworst = Math.Max(bworst, Math.Abs(Db(At(bent, fund[k], 4800)) - Db(At(plain, fund[k], 4800))));+ yield return (bworst <= 0.5 && At(bent, 220, 4800) > 4 * At(plain, 220, 4800) && At(bent, 196, 4800) < 0.5 * At(plain, 196, 4800),+ $"a per-note bend of +2 st moves G3 to A3 and leaves the others (within {bworst:0.00} dB)");++ var chan = Expr((xe, xt) => xe.TrackNoteExpression(xt, -1, NoteExpressionDim.Pressure, 1f));+ int brighter = 0;+ for (int k = 0; k < six.Length; k++) if (Db(At(chan, fund[k] * 3, 4800)) - Db(At(plain, fund[k] * 3, 4800)) > 1) brighter++;+ yield return (brighter == six.Length, $"channel pressure opens every voice ({brighter}/{six.Length} brighter)");++ var padX = Expr((xe, xt) => { P(xe, xt, "lo.a.o1bal", 0f); P(xe, xt, "lo.a.mmcut", 0.5f); P(xe, xt, "padx", 1f); });+ var padX0 = Expr((xe, xt) => { P(xe, xt, "lo.a.o1bal", 0f); P(xe, xt, "lo.a.mmcut", 0.5f); });+ var padY = Expr((xe, xt) => { P(xe, xt, "lo.b.ldcut", 0.9f); P(xe, xt, "pady", 1f); });+ var padY0 = Expr((xe, xt) => P(xe, xt, "lo.b.ldcut", 0.9f));+ yield return (Diff(padX, padX0) > 0.01 && Diff(padY, padY0) > 0.01, "the pad's X moves the multimode cutoff and its Y the morph");++ // ---- the matrix (US4) ---------------------------------------------------------------------+ using (var me = new NotaEngine())+ {+ int mt = me.AddTwinTrack();+ var srcBad = new List<string>();+ for (int k = 0; k < TwinMatrix.Sources.Length; k++)+ {+ P(me, mt, "lo.m64.src", k / 63f);+ if (me.PluginParamText(mt, -1, Pi(me, mt, "lo.m64.src")) != TwinMatrix.Sources[k]) srcBad.Add(TwinMatrix.Sources[k]);+ }+ var dstBad = new List<string>();+ for (int k = 0; k < TwinMatrix.DestinationCount; k++)+ {+ P(me, mt, "lo.m64.dst", k / 255f);+ string dn = me.PluginParamText(mt, -1, Pi(me, mt, "lo.m64.dst"));+ if (dn != TwinMatrix.DestinationName(me, mt, k)) dstBad.Add($"{k}:{dn}");+ }+ P(me, mt, "lo.m64.dst", TwinMatrix.DestinationCount / 255f);+ yield return (srcBad.Count == 0 && dstBad.Count == 0 && me.PluginParamText(mt, -1, Pi(me, mt, "lo.m64.dst")) == "",+ $"the app's matrix tables match the engine's ({TwinMatrix.Sources.Length} sources, {TwinMatrix.DestinationCount} destinations){(srcBad.Count + dstBad.Count > 0 ? " — " + string.Join(", ", srcBad.Concat(dstBad)) : "")}");++ P(me, mt, "lo.m64.src", 0f); P(me, mt, "lo.m64.dst", 0f);+ me.ClearUndoHistory();+ var before = TwinMatrix.Routes(me, mt).Count;+ int slot = TwinMatrix.Add(me, mt, 2, TwinMatrix.DestinationOfSide("o1wave"), 0.5f, -0.5f);+ bool added = slot == 7 && TwinMatrix.Routes(me, mt).Count == before + 1;+ bool undone = me.Undo() && TwinMatrix.Routes(me, mt).Count == before && !me.CanUndo;+ int filled = 0;+ while (TwinMatrix.Add(me, mt, 1, TwinMatrix.DestinationOfSide("ldcut"), 0.1f, 0.1f) > 0) filled++;+ yield return (added && undone && filled == 64 - before && TwinMatrix.Add(me, mt, 1, 1, 0.1f, 0.1f) == -1,+ $"a route lands in the first free slot and undoes in one step; the matrix fills at 64 and then refuses ({before} defaults + {filled})");+ TwinMatrix.Remove(me, mt, 30);+ yield return (TwinMatrix.Routes(me, mt).Count == 63 && TwinMatrix.Add(me, mt, 1, 1, 0.1f, 0.1f) == 30, "removing a route frees its slot");+ }++ // A route of depth 0 changes nothing; a depth on B only follows the morph.+ void Lfo2Cut(NotaEngine xe, int xt, float a, float b)+ {+ P(xe, xt, "lo.m7.src", 2 / 63f); P(xe, xt, "lo.m7.dst", TwinMatrix.DestinationOfSide("ldcut") / 255f);+ P(xe, xt, "lo.a.m7amt", 0.5f + 0.5f * a); P(xe, xt, "lo.b.m7amt", 0.5f + 0.5f * b);+ P(xe, xt, "lo.a.lfo2rate", 0.8f); P(xe, xt, "lo.b.lfo2rate", 0.8f);+ }+ var none = Chord((xe, xt) => P(xe, xt, "lo.a.ldcut", 0.5f));+ var zero = Chord((xe, xt) => { P(xe, xt, "lo.a.ldcut", 0.5f); Lfo2Cut(xe, xt, 0f, 0f); });+ yield return (Diff(none, zero) == 0, $"a route of depth 0 renders exactly like no route (max diff {Diff(none, zero):G3})");+ var onlyB0 = Chord((xe, xt) => { P(xe, xt, "lo.a.ldcut", 0.5f); P(xe, xt, "lo.b.ldcut", 0.5f); Lfo2Cut(xe, xt, 0f, 0.6f); });+ var onlyB1 = Chord((xe, xt) => { P(xe, xt, "lo.a.ldcut", 0.5f); P(xe, xt, "lo.b.ldcut", 0.5f); Lfo2Cut(xe, xt, 0f, 0.6f); P(xe, xt, "lo.morph", 1f); });+ yield return (Diff(onlyB0, none) == 0 && Diff(onlyB1, none) > 0.01, "a route deep on side B only moves the sound as the morph reaches B");++ // Pressure → Morph (the default cutoff routes cleared): only the pressed note morphs.+ float[] PressMorph(bool press) => Expr((xe, xt) =>+ {+ for (int r = 1; r <= 6; r++) P(xe, xt, $"lo.m{r}.dst", 0f);+ TwinMatrix.Add(xe, xt, 10, 1, 1f, 1f);+ P(xe, xt, "lo.b.ldcut", 0.95f); P(xe, xt, "lo.b.ldres", 0.4f);+ if (press) xe.TrackNoteExpression(xt, 55, NoteExpressionDim.Pressure, 1f);+ });+ var pm0 = PressMorph(false);+ var pm1 = PressMorph(true);+ double mworst = 0;+ for (int k = 0; k < six.Length; k++)+ if (six[k] != 55) mworst = Math.Max(mworst, Math.Abs(Db(At(pm1, fund[k], 4800)) - Db(At(pm0, fund[k], 4800))));+ double mself = Math.Abs(Db(At(pm1, 196 * 3, 4800)) - Db(At(pm0, 196 * 3, 4800)));+ yield return (mworst <= 0.5 && mself > 1, $"pressure routed to the Morph morphs only the pressed note (others within {mworst:0.00} dB, its 3rd harmonic {mself:+0.0;-0.0} dB)");++ // MCP: read the patch and set a route by name.+ using (var ce = new NotaEngine())+ {+ int ct = ce.AddTwinTrack();+ var mcp = new Nota.Mcp.Tools.TwinTools(ce, new SyncDispatch(), new NoRefresh());+ P(ce, ct, "lo.b.ldcut", 0.9f);+ string r1 = mcp.SetTwinRoute(ct, "lfo 3", "Osc1 Wave", 40, -20).Result;+ string r2 = mcp.SetTwinRoute(ct, "Nope", "Morph").Result;+ var rd = mcp.ReadTwin(ct).Result!;+ bool routeOk = r1.StartsWith("slot 7: LFO 3 → Osc1 Wave") && r2.StartsWith("error") && rd.Routes.Length == 7+ && rd.Routes[^1] is { Source: "LFO 3", Destination: "Osc1 Wave", DepthAPercent: 40, DepthBPercent: -20 };+ bool readOk = rd.Sound.Any(x => x.Id == "ldcut" && x.Differs) && rd.Summary.Contains("1 of") && ce.Undo() && TwinMatrix.Routes(ce, ct).Count == 6;+ yield return (routeOk && readOk, $"MCP set_twin_route adds a named route in one undo step and read_twin reports sides and routes ({r1} | {r2})");+ yield return (mcp.ReadTwin(ce.AddVoltSynthTrack()).Result is null, "read_twin answers null for another instrument");+ P(ce, ct, "mode", 1f); P(ce, ct, "splitkey", 48f / 127f); P(ce, ct, "share", 0.25f);+ string cpart = mcp.CopyTwinPart(ct, "lower_to_upper").Result;+ var up = mcp.ReadTwin(ct, "up").Result!;+ bool partsOk = cpart.StartsWith("lower_to_upper:") && up.Parts is { Layout: "Split", SplitKey: "C3", LowerVoices: 4, UpperVoices: 8 }+ && up.Routes.Length == 6 && up.Summary.Contains("Split at C3 4 + 8") && up.Summary.Contains("Upper");+ yield return (partsOk && ce.Undo() && G(ce, ct, "up.b.ldcut") != 0.9f, $"MCP copy_twin_part copies a part in one undo step; read_twin reports the layout ({up.Summary})");+ P(ce, ct, "mode", 0f);+ string sm = mcp.SetTwinMorphSide(ct, "b", "o1wave=1; ldres=0.6, nope=1").Result;+ bool sideSet = sm.StartsWith("error: unknown or malformed: nope") && G(ce, ct, "lo.b.o1wave") == 1f && Math.Abs(G(ce, ct, "lo.b.ldres") - 0.6f) < 1e-6 && G(ce, ct, "lo.a.o1wave") != 1f;+ string cp = mcp.CopyTwinSide(ct, "b_to_a").Result;+ bool copiedA = cp.StartsWith("b_to_a: 164") && G(ce, ct, "lo.a.o1wave") == 1f && ce.Undo() && G(ce, ct, "lo.a.o1wave") != 1f;+ yield return (sideSet && copiedA, $"MCP set_twin_morph_side writes one side, copy_twin_side copies it in one undo step ({sm} | {cp})");+ }++ // ---- effects (US5) ------------------------------------------------------------------------+ float[] Fx(Action<NotaEngine, int> setup, int bpm = 120, double secs = 2.0, double noteBeats = 3.5)+ {+ using var fe = new NotaEngine();+ fe.SetBpm(bpm);+ int ft = fe.AddTwinTrack();+ setup(fe, ft);+ fe.AddMidiClip(ft, 0.0, 16.0);+ fe.SetClipNotes(ft, 0, new[] { 48, 55, 60, 64 }.Select(n => new NotaNote(n, 0, noteBeats, 0.8f)).ToArray());+ var o = new float[(int)(secs * Sr) * 2];+ var tmp = new float[256 * 2];+ fe.Seek(0); fe.Play();+ for (int done = 0; done < o.Length / 2;) { int m = Math.Min(256, o.Length / 2 - done); fe.RenderOffline(tmp, m, Sr); Array.Copy(tmp, 0, o, done * 2, m * 2); done += m; }+ return o;+ }+ void AllFx(NotaEngine fe, int ft) { P(fe, ft, "lo.a.modfxon", 1f); P(fe, ft, "lo.a.dlyon", 1f); P(fe, ft, "lo.a.revon", 1f); }+ var dry = Fx((fe, ft) => { });+ var bypassed = Fx((fe, ft) => { AllFx(fe, ft); P(fe, ft, "lo.fxon", 0f); });+ yield return (Diff(dry, bypassed) == 0, $"the effects section off renders exactly the voices alone (max diff {Diff(dry, bypassed):G3})");+ var heard = new List<string>();+ foreach (var (name, setup) in new (string, Action<NotaEngine, int>)[]+ {+ ("chorus", (fe, ft) => { P(fe, ft, "lo.a.modfxon", 1f); P(fe, ft, "lo.a.modfxtype", 0f); }),+ ("flanger", (fe, ft) => { P(fe, ft, "lo.a.modfxon", 1f); P(fe, ft, "lo.a.modfxtype", 1f / 3f); }),+ ("phaser", (fe, ft) => { P(fe, ft, "lo.a.modfxon", 1f); P(fe, ft, "lo.a.modfxtype", 2f / 3f); }),+ ("ensemble", (fe, ft) => { P(fe, ft, "lo.a.modfxon", 1f); P(fe, ft, "lo.a.modfxtype", 1f); }),+ ("delay", (fe, ft) => P(fe, ft, "lo.a.dlyon", 1f)),+ ("reverb", (fe, ft) => P(fe, ft, "lo.a.revon", 1f)),+ })+ {+ var w = Fx(setup);+ if (w.All(float.IsFinite) && Diff(w, dry) > 0.005 && Peak(w) < 1.0) heard.Add(name);+ }+ yield return (heard.Count == 6, $"every effect is heard, finite, under 0 dBFS ({string.Join(", ", heard)})");++ // A synced 1/4 delay of a short note: the echo lands a beat later at either tempo.+ double EchoAt(int bpm)+ {+ var o = Fx((fe, ft) => { P(fe, ft, "lo.a.dlyon", 1f); P(fe, ft, "lo.a.dlysync", 1f); P(fe, ft, "lo.a.dlydiv", 5f / 7f);+ P(fe, ft, "lo.a.dlyfb", 0f); P(fe, ft, "lo.a.dlymix", 0.5f); P(fe, ft, "lo.a.dlypingpong", 0f); P(fe, ft, "lo.a.aenvr", 0.05f); }, bpm, 1.5, 0.1);+ // From the direct sound's loudest window to the echo's: the note's own rise cancels out.+ int win = Sr / 200, split = (int)(0.25 * 60.0 / bpm * Sr);+ int Loudest(int from, int to)+ {+ int best = from; double bestE = -1;+ for (int at = from; at + win < to; at += win)+ {+ double en = 0;+ for (int i = at; i < at + win; i++) en += o[2 * i] * (double)o[2 * i];+ if (en > bestE) { bestE = en; best = at; }+ }+ return best;+ }+ return (Loudest(split, o.Length / 2) - Loudest(0, split)) / (double)Sr;+ }+ double e120 = EchoAt(120), e90 = EchoAt(90);+ yield return (Math.Abs(e120 - 0.5) < 0.03 && Math.Abs(e90 - 2.0 / 3.0) < 0.03, $"a synced 1/4 delay follows the tempo (echo {e120:0.000} s after the note at 120 BPM, {e90:0.000} s at 90)");++ // A long reverb keeps ringing after the note: the instrument doesn't sleep through its tail.+ var tail = Fx((fe, ft) => { P(fe, ft, "lo.a.revon", 1f); P(fe, ft, "lo.a.revsize", 1f); P(fe, ft, "lo.a.revmix", 0.6f); P(fe, ft, "lo.a.aenvr", 0.05f); }, 120, 6.0, 0.5);+ var noRev = Fx((fe, ft) => P(fe, ft, "lo.a.aenvr", 0.05f), 120, 6.0, 0.5);+ double Win(float[] o, double t0, double t1) { double en = 0; int a = (int)(t0 * Sr), b = (int)(t1 * Sr); for (int i = a; i < b; i++) en += o[2 * i] * (double)o[2 * i]; return Math.Sqrt(en / (b - a)); }+ yield return (Win(tail, 1.0, 1.5) > 1e-3 && Win(noRev, 1.0, 1.5) < 1e-5, $"a reverb tail rings past the note ({Db(Win(tail, 1.0, 1.5)):0} dB 0.75 s after it, {Db(Win(noRev, 1.0, 1.5)):0} dB without)");+++ // ---- the sequencer (US8) --------------------------------------------------------------------+ foreach (var r in SequencerChecks()) yield return r;++ // ---- Split / Layer (US9) ------------------------------------------------------------------+ foreach (var r in PartChecks()) yield return r;+ foreach (var r in EdgeChecks()) yield return r;+ foreach (var r in ReviewChecks()) yield return r;+ }++ // Lower panned hard left, Upper hard right, so a channel says which part played.+ private static (NotaEngine E, int T) PartRig(int mode, float splitKey = 48f / 127f, float share = 0.5f)+ {+ var e = new NotaEngine();+ int t = e.AddTwinTrack();+ P(e, t, "mode", mode / 2f); P(e, t, "splitkey", splitKey); P(e, t, "share", share);+ P(e, t, "lo.pan", 0f); P(e, t, "up.pan", 1f);+ P(e, t, "lo.a.spread", 0f); P(e, t, "up.a.spread", 0f);+ Render(e, 512);+ return (e, t);+ }+ private static double Ch(float[] st, int ch) { double s = 0; for (int i = ch; i < st.Length; i += 2) s += st[i] * (double)st[i]; return Math.Sqrt(s / (st.Length / 2)); }++ private static IEnumerable<(bool, string)> PartChecks()+ {+ {+ var (e, t) = PartRig(2);+ using (e)+ {+ e.TrackNoteOn(t, 47, 0.8f);+ var lowKey = Render(e, Sr / 2);+ e.TrackNoteOff(t, 47); Render(e, Sr);+ e.TrackNoteOn(t, 48, 0.8f);+ var highKey = Render(e, Sr / 2);+ yield return (Ch(lowKey, 0) > 100 * Ch(lowKey, 1) && Ch(highKey, 1) > 100 * Ch(highKey, 0),+ $"Split at C3: B2 plays the Lower part, C3 the Upper (B2 L {Db(Ch(lowKey, 0)):0} / R {Db(Ch(lowKey, 1)):0} dB; C3 L {Db(Ch(highKey, 0)):0} / R {Db(Ch(highKey, 1)):0} dB)");+ }+ }+ {+ var (e, t) = PartRig(2, 60f / 127f, 0.25f); // Lower 4, Upper 8+ using (e)+ {+ foreach (var n in new[] { 36, 38, 40, 41, 43, 45 }) e.TrackNoteOn(t, n, 0.8f);+ foreach (var n in new[] { 60, 62, 64, 65, 67, 69, 71, 72, 74 }) e.TrackNoteOn(t, n, 0.8f);+ Render(e, 4096);+ var sc = new float[32];+ e.InstrumentScope(t, sc);+ yield return (sc[4] == 4 && sc[5] == 8, $"a 4 + 8 share: six low keys sound on 4 voices, nine high ones on Upper's 8 ({sc[4]} + {sc[5]})");+ }+ }+ {+ var (e, t) = PartRig(1);+ using (e)+ {+ e.TrackNoteOn(t, 60, 0.8f);+ var both = Render(e, Sr / 2);+ yield return (e.InstrumentVoiceCount(t) == 2 && Ch(both, 0) > 1e-3 && Ch(both, 1) > 1e-3, "Layer: one key plays both parts, each through its own pan");+ foreach (var n in new[] { 48, 52, 55 }) e.TrackNoteOn(t, n, 0.8f);+ Render(e, 2048);+ P(e, t, "mode", 0f); // back to Single with keys down+ Render(e, 2048);+ foreach (var n in new[] { 48, 52, 55, 60 }) e.TrackNoteOff(t, n);+ var rest = Render(e, Sr * 2);+ yield return (e.InstrumentVoiceCount(t) == 0 && Rms(rest, Sr) < 1e-5, $"changing the layout with keys down leaves no note hanging ({e.InstrumentVoiceCount(t)} voices)");+ }+ }+ {+ // The sequencer on Upper only, in a Layer.+ var (e, t) = SeqRig(120, Enumerable.Repeat("C3:100:50%", 8).ToArray(), (x, y) =>+ {+ P(x, y, "mode", 0.5f); P(x, y, "seq.target", 0.5f); P(x, y, "lo.a.spread", 0f); P(x, y, "up.a.spread", 0f); P(x, y, "lo.pan", 0f); P(x, y, "up.pan", 1f);+ P(x, y, "up.a.o1level", 0f); P(x, y, "up.a.noiselevel", 1f); P(x, y, "up.a.aenva", 0f);+ });+ using (e)+ {+ var o = Roll(e, 1.0);+ yield return (Ch(o, 1) > 1e-3 && Ch(o, 0) < 1e-6, $"seq.target Upper: the pattern plays only the Upper part (L {Db(Ch(o, 0)):0} / R {Db(Ch(o, 1)):0} dB)");+ }+ }+ // Part edits (FR-075): copy Lower → Upper, then load a preset into Upper of a Single patch.+ using (var pe = new NotaEngine())+ {+ int pt = pe.AddTwinTrack();+ P(pe, pt, "lo.a.ldcut", 0.2f); P(pe, pt, "lo.b.o1wave", 1f); P(pe, pt, "lo.voicemode", 1f);+ pe.ClearUndoHistory();+ int wrote = Nota.Application.Twin.TwinParts.Apply(pe, pt, Nota.Application.Twin.TwinParts.Edit.CopyLowerToUpper);+ bool copied = G(pe, pt, "up.a.ldcut") == 0.2f && G(pe, pt, "up.b.o1wave") == 1f && G(pe, pt, "up.voicemode") == 1f;+ bool undone = pe.Undo() && G(pe, pt, "up.a.ldcut") != 0.2f && !pe.CanUndo;+ yield return (copied && undone, $"Copy Lower → Upper moves the whole part in one undo step (wrote {wrote})");++ var preset = new Dictionary<string, float> { ["lo.a.ldcut"] = 0.8f, ["lo.morph"] = 0.3f, ["lo.m1.src"] = 0f };+ string warn = Nota.Application.Twin.TwinParts.LoadIntoPart(pe, pt, preset, "up");+ bool loaded = warn == "" && G(pe, pt, "up.a.ldcut") == 0.8f && G(pe, pt, "up.morph") == 0.3f && G(pe, pt, "lo.a.ldcut") == 0.2f+ && G(pe, pt, "mode") == 0.5f && G(pe, pt, "up.b.o1wave") == pe.InstrumentParamDefault(pt, Pi(pe, pt, "up.b.o1wave"));+ bool back = pe.Undo() && G(pe, pt, "mode") == 0f && G(pe, pt, "up.a.ldcut") != 0.8f && !pe.CanUndo;+ yield return (loaded && back, "Load into Upper of a Single patch: Upper takes the preset, the current sound stays Lower, Layer — one undo step");++ // A saved user preset loads into a part the same way (FR-075).+ string pdir = Path.Combine(Path.GetTempPath(), "nota-twin-presets-" + Guid.NewGuid().ToString("N"));+ try+ {+ int src = pe.AddTwinTrack();+ P(pe, src, "lo.a.ldcut", 0.37f); P(pe, src, "lo.b.o2wave", 1f);+ var store = new PresetStore();+ bool saved = store.Save(pe, src, -1, "My Twin", pdir);+ var file = new PresetLibrary().List(pdir).FirstOrDefault(x => x.DisplayName == "My Twin");+ var prm = file.Path is null ? null : store.InstrumentParams(file.Path);+ bool ok = saved && prm is not null && store.Describe(file.Path!) is { BuiltinKind: 18 }+ && TwinParts.LoadIntoPart(pe, pt, prm, "up") == "" && G(pe, pt, "up.a.ldcut") == 0.37f && G(pe, pt, "up.b.o2wave") == 1f;+ yield return (ok, "a saved Twin preset loads into the Upper part (the card's Parts › Load into Upper lists it)");+ }+ finally { try { Directory.Delete(pdir, true); } catch (IOException) { } }+ }+ }++ // A Twin with a clicky test voice (noise through an open ladder, instant attack, quick release,+ // no drift, no effects), the sequencer on at 1/16 playing `rows`, the transport rolling.+ private static (NotaEngine E, int T) SeqRig(int bpm, string[] rows, Action<NotaEngine, int>? setup = null)+ {+ var e = new NotaEngine();+ e.SetBpm(bpm);+ int t = e.AddTwinTrack();+ foreach (var (id, v) in new[] { ("lo.a.o1level", 0f), ("lo.a.noiselevel", 1f), ("lo.a.ldcut", 1f), ("lo.a.aenva", 0f), ("lo.a.aenvr", 0f),+ ("lo.a.drift", 0f), ("seq.on", 1f), ("seq.rate", 0.6f) })+ P(e, t, id, v);+ TwinPatterns.WritePattern(e, t, 0, rows);+ setup?.Invoke(e, t);+ return (e, t);+ }+ private static float[] Roll(NotaEngine e, double secs, int block = 512, Action<int>? atBlock = null)+ {+ var o = new float[(int)(secs * Sr) * 2];+ var tmp = new float[block * 2];+ e.Seek(0); e.Play();+ for (int done = 0, b = 0; done < o.Length / 2; b++) { atBlock?.Invoke(b); int m = Math.Min(block, o.Length / 2 - done); e.RenderOffline(tmp, m, Sr); Array.Copy(tmp, 0, o, done * 2, m * 2); done += m; }+ return o;+ }+ // Sample indices where the sound starts after at least `gap` samples of silence.+ private static List<int> Onsets(float[] st, int gap = 64)+ {+ var l = new List<int>();+ int quiet = gap;+ for (int i = 0; i < st.Length / 2; i++)+ {+ bool loud = Math.Abs(st[2 * i]) > 1e-7f || Math.Abs(st[2 * i + 1]) > 1e-7f;+ if (loud && quiet >= gap) l.Add(i);+ quiet = loud ? 0 : quiet + 1;+ }+ return l;+ }++ // ---- determinism and edge cases (T082, T083) ----------------------------------------------+ // A patch that uses everything that could drift: two layered parts, drift, the Random source,+ // effects, a sequencer pattern with a motion lane, and a clip.+ private static void Rich(NotaEngine e, int t)+ {+ P(e, t, "mode", 0.5f);+ foreach (var part in new[] { "lo", "up" })+ {+ P(e, t, $"{part}.a.drift", 0.8f); P(e, t, $"{part}.a.o2level", 0.7f); P(e, t, $"{part}.b.ldcut", 0.85f); P(e, t, $"{part}.morph", 0.4f);+ P(e, t, $"{part}.a.dlyon", 1f); P(e, t, $"{part}.a.revon", 1f); P(e, t, $"{part}.a.modfxon", 1f);+ TwinMatrix.Add(e, t, Array.IndexOf(TwinMatrix.Sources, "Random"), TwinMatrix.DestinationOfSide("mmcut"), 0.4f, 0.4f, part);+ }+ P(e, t, "up.octave", 0.75f);+ P(e, t, "seq.on", 1f); P(e, t, "seq.target", 0f);+ TwinPatterns.WritePattern(e, t, 0, new[] { "C3 G3:110:50%", ".", "A2:80:tie", "A2:70:30%", "D#3:90:60%", ".", "G3:100:40%", "F3:90:50%" });+ TwinPatterns.Do(e, t, TwinPatterns.Act.MotionTarget, Pi(e, t, "lo.morph"));+ for (int k = 0; k < 8; k++) TwinPatterns.Do(e, t, TwinPatterns.Act.MotionSet, k, k / 7f);+ e.AddMidiClip(t, 0.0, 8.0);+ e.SetClipNotes(t, 0, new[] { new NotaNote(72, 0.5, 1.5, 0.8f), new NotaNote(76, 2.0, 1.0, 0.6f) });+ e.ClearUndoHistory();+ }++ private static float[] Take(NotaEngine e, int frames, double sr = Sr, int block = 512)+ {+ var o = new float[frames * 2];+ var tmp = new float[block * 2];+ e.Seek(0); e.Play();+ for (int done = 0; done < frames;) { int m = Math.Min(block, frames - done); e.RenderOffline(tmp, m, sr); Array.Copy(tmp, 0, o, done * 2, m * 2); done += m; }+ e.StopTransport();+ return o;+ }++ // Transport stopped until the voices and the effects' tails are gone: the next start is a+ // silent one, which re-seeds the instrument (so it renders as a fresh one would).+ private static void Settle(NotaEngine e, double sr = Sr)+ {+ var tmp = new float[4096 * 2];+ for (int k = 0; k < 6 * (int)sr / 4096; k++) e.RenderOffline(tmp, 4096, sr);+ }++ private static IEnumerable<(bool, string)> EdgeChecks()+ {+ // SC-006: an idle Twin (no notes, tails gone; a stopped sequencer included) costs what an+ // empty track does. Render time, best of five, transport stopped.+ double Cost(Action<NotaEngine>? setup)+ {+ using var e = new NotaEngine();+ e.SetBpm(120);+ setup?.Invoke(e);+ var tmp = new float[512 * 2];+ for (int k = 0; k < 8 * Sr / 512; k++) e.RenderOffline(tmp, 512, Sr); // let every tail die+ double best = double.MaxValue;+ for (int run = 0; run < 5; run++)+ {+ var sw = System.Diagnostics.Stopwatch.StartNew();+ for (int k = 0; k < 5 * Sr / 512; k++) e.RenderOffline(tmp, 512, Sr);+ best = Math.Min(best, sw.Elapsed.TotalMilliseconds);+ }+ return best;+ }+ double empty = Cost(e => e.AddAudioTrack());+ double idleTwin = Cost(e => { int t = e.AddTwinTrack(); Rich(e, t); e.TrackNoteOn(t, 60, 0.8f); e.RenderOffline(new float[1024], 512, Sr); e.TrackNoteOff(t, 60); });+ double busy = Cost(e => { int t = e.AddTwinTrack(); foreach (var n in new[] { 48, 52, 55, 59 }) e.TrackNoteOn(t, n, 0.8f); });+ yield return (idleTwin <= empty * 1.5 + 2.0 && busy > idleTwin * 5,+ $"SC-006: an idle Twin with a stopped sequencer costs what an empty track does ({idleTwin:0.0} vs {empty:0.0} ms per 5 s; a held chord {busy:0} ms)");++ // FR-030: the release velocity of a note-off reaches the matrix ("Release velocity").+ double Tail(float? relVel)+ {+ using var e = new NotaEngine();+ int t = e.AddTwinTrack();+ P(e, t, "lo.a.aenvr", 0.25f);+ TwinMatrix.Add(e, t, Array.IndexOf(TwinMatrix.Sources, "Release velocity"), TwinMatrix.DestinationOfSide("aenvr"), 1f, 1f);+ Render(e, 512);+ e.TrackNoteOn(t, 60, 0.8f);+ Render(e, Sr / 4);+ if (relVel is float rv) e.TrackNoteOffVelocity(t, 60, rv); else e.TrackNoteOff(t, 60);+ Render(e, Sr / 10);+ return Rms(Render(e, Sr / 2));+ }+ // …and through an Instrument Rack to a Twin on a chain.+ double RackTail(float relVel)+ {+ using var e = new NotaEngine();+ int r = e.AddInstrumentRackTrack();+ e.RackAddChain(r, 18);+ void C(string id, float v)+ {+ for (int i = 0; i < e.RackChainInstrumentParamCount(r, 0); i++)+ if (e.RackChainInstrumentParamId(r, 0, i) == id) { e.RackChainInstrumentParamSet(r, 0, i, v); return; }+ }+ C("lo.a.aenvr", 0.25f); C("lo.b.aenvr", 0.25f);+ C("lo.m7.src", Array.IndexOf(TwinMatrix.Sources, "Release velocity") / 63f);+ C("lo.m7.dst", TwinMatrix.DestinationOfSide("aenvr") / 255f);+ C("lo.a.m7amt", 1f); C("lo.b.m7amt", 1f);+ Render(e, 512);+ e.TrackNoteOn(r, 60, 0.8f);+ Render(e, Sr / 4);+ e.TrackNoteOffVelocity(r, 60, relVel);+ Render(e, Sr / 10);+ return Rms(Render(e, Sr / 2));+ }+ double rSoft = RackTail(0.05f), rHard = RackTail(1f);+ yield return (Db(rHard) - Db(rSoft) > 6, $"release velocity reaches a Twin on an Instrument Rack chain ({Db(rSoft):0} / {Db(rHard):0} dB)");+ double soft = Tail(0.05f), hard = Tail(1f), none = Tail(null);+ yield return (Db(hard) - Db(soft) > 6 && Math.Abs(Db(none) - Db(soft)) < 3,+ $"release velocity drives a route: a hard release rings longer ({Db(soft):0} / {Db(hard):0} dB; no velocity {Db(none):0} dB)");++ const int N = Sr * 3;+ float[] first;+ using (var e = new NotaEngine()) { e.SetBpm(120); int t = e.AddTwinTrack(); Rich(e, t); first = Take(e, N); }+ float[] again;+ using (var e = new NotaEngine()) { e.SetBpm(120); int t = e.AddTwinTrack(); Rich(e, t); again = Take(e, N, block: 333); }+ yield return (Rms(first) > 1e-3 && Diff(first, again) == 0, $"SC-008: a project with drift, Random, FX and the sequencer renders identically twice (maxdiff {Diff(first, again):G3})");++ // Save / load: the reloaded project renders the same.+ string dir = Path.Combine(Path.GetTempPath(), "nota-twin-" + Guid.NewGuid().ToString("N"));+ try+ {+ var transport = new TransportState(120.0, 1.0, false, false);+ using (var e = new NotaEngine()) { e.SetBpm(120); int t = e.AddTwinTrack(); Rich(e, t); ProjectService.Save(ProjectService.Capture(e, transport, new List<string>()), dir, e); }+ using var r = new NotaEngine();+ var warn = ProjectService.Apply(ProjectService.Load(dir), r, dir);+ r.SetBpm(120);+ var back = Take(r, N);+ yield return (warn.Count == 0 && Diff(first, back) == 0, $"SC-008: after save / load the project renders identically ({warn.Count} warnings, maxdiff {Diff(first, back):G3})");+ }+ finally { try { Directory.Delete(dir, true); } catch (IOException) { } }++ // Another sample rate: the patch sounds the same, and coming back renders identically.+ using (var e = new NotaEngine())+ {+ e.SetBpm(120); int t = e.AddTwinTrack(); Rich(e, t);+ var hi = Take(e, N * 2, 96000);+ Settle(e, 96000);+ var back = Take(e, N);+ double dl = Db(Rms(hi)) - Db(Rms(first));+ yield return (hi.All(float.IsFinite) && Math.Abs(dl) < 1.0 && Diff(first, back) == 0,+ $"at 96 kHz the patch sounds the same ({dl:+0.00;-0.00} dB), and back at 48 kHz it renders identically (maxdiff {Diff(first, back):G3})");+ }++ // Freeze: the frozen audio is the live render.+ using (var e = new NotaEngine())+ {+ e.SetBpm(120); int t = e.AddTwinTrack(); Rich(e, t);+ var live = Take(e, N);+ Settle(e);+ e.Stop(); e.SetLoop(false, 0, 0); e.SetMetronome(false); e.StopTransport();+ long total = e.BeginFreeze(t, 6.0);+ e.StopTransport(); e.Seek(0); e.Play();+ var chunk = new float[4096 * 2];+ for (long rem = total; rem > 0;) { int m = (int)Math.Min(4096, rem); e.RenderOffline(chunk, m); rem -= m; }+ e.StopTransport(); e.EndFreeze(t);+ Settle(e);+ var frozen = Take(e, N);+ yield return (e.IsTrackFrozen(t) && Diff(live, frozen) < 1e-4, $"a frozen Twin plays its live render (maxdiff {Diff(live, frozen):G3})");+ }++ // Copy / paste the instrument, and a Twin on an Instrument Rack chain duplicated with its track.+ using (var e = new NotaEngine())+ {+ e.SetBpm(120); int t = e.AddTwinTrack(); Rich(e, t);+ int dst = e.AddInstrumentTrack();+ bool copied = e.CopyDevices(t, Array.Empty<int>(), true, Array.Empty<int>()) == 1;+ e.PasteDevices(dst, -1, -1, out _);+ bool same = e.TrackInstrumentKind(dst) == 18 && e.GetPluginState(dst, -1).SequenceEqual(e.GetPluginState(t, -1));+ yield return (copied && same, "copy / paste of a Twin brings both parts, both sides, the matrix, the effects and the patterns");+ }+ using (var e = new NotaEngine())+ {+ int rack = e.AddInstrumentRackTrack();+ bool set = e.RackAddChain(rack, 18) == 0 && e.RackChainInstrumentKind(rack, 0) == 18; // a new rack starts empty+ int ci = -1;+ for (int i = 0; i < e.RackChainInstrumentParamCount(rack, 0); i++) if (e.RackChainInstrumentParamId(rack, 0, i) == "lo.b.ldcut") ci = i;+ if (ci >= 0) e.RackChainInstrumentParamSet(rack, 0, ci, 0.123f);+ int dup = e.DuplicateTrack(rack);+ bool kept = set && ci >= 0 && dup > 0 && e.RackChainInstrumentKind(dup, 0) == 18 && Math.Abs(e.RackChainInstrumentParamGet(dup, 0, ci) - 0.123f) < 1e-6;+ e.TrackNoteOn(rack, 60, 0.8f);+ var rb = Render(e, Sr / 2);+ yield return (kept && Rms(rb) > 1e-3 && rb.All(float.IsFinite),+ $"a Twin on an Instrument Rack chain plays, and duplicating the track keeps its side B ({Db(Rms(rb)):0} dB)");+ }+ }++ private static IEnumerable<(bool, string)> SequencerChecks()+ {+ // Edits are undo steps; the state carries the patterns.+ using (var e = new NotaEngine())+ {+ int t = e.AddTwinTrack();+ e.ClearUndoHistory();+ TwinPatterns.Do(e, t, TwinPatterns.Act.AddStepNote, 3 << 8 | 60, 0.7f);+ var after = TwinPatterns.FromState(e.GetPluginState(t, -1))!;+ bool added = after[0].Steps[3].Notes.SequenceEqual(new[] { 60 }) && after[0].Steps[3].Velocity == 89;+ bool undone = e.Undo() && TwinPatterns.FromState(e.GetPluginState(t, -1))![0].Steps[3].IsRest && !e.CanUndo;+ bool redone = e.Redo() && TwinPatterns.FromState(e.GetPluginState(t, -1))![0].Steps[3].Notes.Count == 1;+ yield return (added && undone && redone, "a pattern edit is one undo step, and redo brings it back");+ string err = TwinPatterns.WritePattern(e, t, 2, new[] { "C3 E3 G3:100:50%", ".", "A2:90:tie", "A2:90:25%" });+ int t2 = e.AddTwinTrack();+ e.SetPluginState(t2, -1, e.GetPluginState(t, -1));+ var p2 = TwinPatterns.FromState(e.GetPluginState(t2, -1))![2];+ yield return (err == "" && p2.Length == 4 && TwinPatterns.StepText(p2.Steps[0]) == "C3 E3 G3:100:50%" && p2.Steps[1].IsRest+ && p2.Steps[2].Gate == TwinPatterns.GateTie,+ $"patterns round-trip through the text form and the state ({TwinPatterns.StepText(p2.Steps[0])} | {TwinPatterns.StepText(p2.Steps[2])})");+ }++ // SC-009: over 64 bars, at 60, 120 and 200 BPM, every 1/16 step lands within one sample+ // of the grid (onsets found while rendering, so the long runs keep no audio). A square+ // wave, not noise: its first sample is never near zero, so the detector can't be late.+ var rows = Enumerable.Repeat("C4:100:25%", 16).ToArray();+ foreach (int bpm in new[] { 60, 120, 200 })+ {+ var (e, t) = SeqRig(bpm, rows, (x, y) => { P(x, y, "lo.a.noiselevel", 0f); P(x, y, "lo.a.o1level", 1f); P(x, y, "lo.a.o1wave", 1f); });+ using (e)+ {+ double spb = 60.0 * Sr / bpm;+ long frames = (long)Math.Ceiling(64 * 4 * spb) - 1;+ var tmp = new float[512 * 2];+ long first = -1, worst = 0, count = 0, quiet = 64;+ e.Seek(0); e.Play();+ for (long done = 0; done < frames;)+ {+ int m = (int)Math.Min(512, frames - done);+ e.RenderOffline(tmp, m, Sr);+ for (int i = 0; i < m; i++)+ {+ bool loud = Math.Abs(tmp[2 * i]) > 1e-7f || Math.Abs(tmp[2 * i + 1]) > 1e-7f;+ if (loud && quiet >= 64)+ {+ long at = done + i;+ if (first < 0) first = at;+ long expect = first + (long)Math.Ceiling(count * 0.25 * spb - 1e-6);+ worst = Math.Max(worst, Math.Abs(at - expect));+ count++;+ }+ quiet = loud ? 0 : quiet + 1;+ }+ done += m;+ }+ yield return (count == 64 * 16 && worst <= 1, $"SC-009: at {bpm} BPM, 64 bars of 1/16 steps land on the grid ({count} onsets, worst {worst} sample off)");+ }+ }++ // The same at any block size; a stop releases everything.+ {+ var (e1, t1) = SeqRig(120, new[] { "C3 G3:100:60%", "E3:80:tie", "E3:80:30%", "." });+ var (e2, t2) = SeqRig(120, new[] { "C3 G3:100:60%", "E3:80:tie", "E3:80:30%", "." });+ using (e1) using (e2)+ {+ var a = Roll(e1, 2.0, 512);+ var b = Roll(e2, 2.0, 77);+ double md = 0;+ for (int i = 0; i < a.Length; i++) md = Math.Max(md, Math.Abs(a[i] - b[i]));+ yield return (Rms(a) > 1e-3 && md == 0, $"a running pattern renders bit-identically at blocks of 512 and 77 (max diff {md:G3})");+ e1.StopTransport();+ var tail = new float[Sr / 2 * 2];+ e1.RenderOffline(tail, Sr / 2, Sr);+ yield return (e1.InstrumentVoiceCount(t1) == 0 && Rms(tail, Sr / 4) < 1e-5, $"stopping the transport releases the sequencer's notes ({e1.InstrumentVoiceCount(t1)} voices)");+ }+ }++ // Step record: a chord held and lifted is one step; the cursor moves on.+ using (var e = new NotaEngine())+ {+ int t = e.AddTwinTrack();+ TwinPatterns.Do(e, t, TwinPatterns.Act.StepRecordArm, 1);+ var blk = new float[512 * 2];+ foreach (var n in new[] { 48, 52, 55 }) e.TrackNoteOn(t, n, 0.9f);+ e.RenderOffline(blk, 512, Sr);+ foreach (var n in new[] { 48, 52, 55 }) e.TrackNoteOff(t, n);+ e.RenderOffline(blk, 512, Sr);+ e.TrackNoteOn(t, 60, 0.5f); e.RenderOffline(blk, 512, Sr); e.TrackNoteOff(t, 60); e.RenderOffline(blk, 512, Sr);+ e.ClearUndoHistory();+ TwinPatterns.Do(e, t, TwinPatterns.Act.StepRecordPoll);+ var pat = TwinPatterns.FromState(e.GetPluginState(t, -1))![0];+ bool rec = pat.Steps[0].Notes.OrderBy(x => x).SequenceEqual(new[] { 48, 52, 55 }) && pat.Steps[1].Notes.SequenceEqual(new[] { 60 });+ var sc = new float[32];+ e.InstrumentScope(t, sc);+ yield return (rec && sc[24] == 2, $"step record: a held chord becomes one step and the cursor moves on (cursor {sc[24]}; steps {TwinPatterns.StepText(pat.Steps[0])} | {TwinPatterns.StepText(pat.Steps[1])})");+ TwinPatterns.Do(e, t, TwinPatterns.Act.StepRecordArm, 0);+ }++ // A held key transposes the pattern from its first note.+ {+ var (e, t) = SeqRig(120, Enumerable.Repeat("C3:100:80%", 8).ToArray(), (x, y) => { P(x, y, "lo.a.o1level", 1f); P(x, y, "lo.a.noiselevel", 0f); P(x, y, "lo.a.ldcut", 0.6f); });+ var (f, u) = SeqRig(120, Enumerable.Repeat("C3:100:80%", 8).ToArray(), (x, y) => { P(x, y, "lo.a.o1level", 1f); P(x, y, "lo.a.noiselevel", 0f); P(x, y, "lo.a.ldcut", 0.6f); });+ using (e) using (f)+ {+ var plain = Roll(e, 1.0);+ var moved = Roll(f, 1.0, 512, b => { if (b == 2) f.TrackNoteOn(u, 52, 0.8f); });+ yield return (At(moved, 164.81, Sr / 2) > 4 * At(plain, 164.81, Sr / 2) && At(moved, 130.81, Sr / 2) < 0.5 * At(plain, 130.81, Sr / 2),+ "holding E3 transposes a C3 pattern to E3 (the key itself doesn't sound)");+ }+ }++ // The arpeggiator walks the held chord, one note at a time, two octaves up.+ {+ var (e, t) = SeqRig(120, new[] { "." }, (x, y) => { P(x, y, "seq.kind", 1f); P(x, y, "arp.oct", 1f / 3f); P(x, y, "lo.a.o1level", 1f); P(x, y, "lo.a.noiselevel", 0f); P(x, y, "lo.a.ldcut", 0.7f); });+ using (e)+ {+ int most = 0;+ var o = Roll(e, 2.0, 512, b =>+ {+ if (b == 1) foreach (var n in new[] { 48, 52, 55 }) e.TrackNoteOn(t, n, 0.8f);+ if (b > 4) most = Math.Max(most, e.InstrumentVoiceCount(t));+ });+ yield return (Rms(o, Sr / 2) > 1e-3 && most <= 2 && At(o, 261.63, Sr / 2) > 0.1 * At(o, 130.81, Sr / 2),+ $"the arpeggiator plays the held chord a note at a time over two octaves (≤ {most} voices sounding)");+ }+ }++ // A motion lane on the Morph moves the sound step by step; recording the lane pauses it.+ {+ var rowsM = Enumerable.Repeat("C3:100:80%", 8).ToArray();+ void Lane(NotaEngine x, int y, bool arm)+ {+ P(x, y, "lo.a.o1level", 1f); P(x, y, "lo.a.noiselevel", 0f); P(x, y, "lo.a.ldcut", 0.3f); P(x, y, "lo.b.ldcut", 0.95f);+ TwinPatterns.Do(x, y, TwinPatterns.Act.MotionTarget, 0 << 16 | Pi(x, y, "lo.morph"));+ for (int k = 0; k < 8; k++) TwinPatterns.Do(x, y, TwinPatterns.Act.MotionSet, 0 << 8 | k, k % 2);+ if (arm) TwinPatterns.Do(x, y, TwinPatterns.Act.MotionRecordArm, 0);+ }+ var (a, ta) = SeqRig(120, rowsM, (x, y) => { P(x, y, "lo.a.o1level", 1f); P(x, y, "lo.a.noiselevel", 0f); P(x, y, "lo.a.ldcut", 0.3f); P(x, y, "lo.b.ldcut", 0.95f); });+ var (b, tb) = SeqRig(120, rowsM, (x, y) => Lane(x, y, false));+ var (c, tc) = SeqRig(120, rowsM, (x, y) => Lane(x, y, true));+ using (a) using (b) using (c)+ {+ var plain = Roll(a, 1.0);+ var moving = Roll(b, 1.0);+ var paused = Roll(c, 1.0);+ yield return (Diff(plain, moving) > 0.01 && Diff(plain, paused) == 0,+ $"a motion lane on the Morph moves the sound; while the lane records, its playback pauses (diff {Diff(plain, paused):G3})");+ }+ }+ // A motion lane can play the expression pad too (FR-063): Pad X → the ladder cutoff.+ {+ var rowsP = Enumerable.Repeat("C3:100:80%", 8).ToArray();+ void Rig(NotaEngine x, int y, bool lane)+ {+ P(x, y, "lo.a.o1level", 1f); P(x, y, "lo.a.noiselevel", 0f); P(x, y, "lo.a.ldcut", 0.4f);+ TwinMatrix.Add(x, y, Array.IndexOf(TwinMatrix.Sources, "Pad X"), TwinMatrix.DestinationOfSide("ldcut"), 0.5f, 0.5f);+ if (!lane) return;+ TwinPatterns.Do(x, y, TwinPatterns.Act.MotionTarget, 0 << 16 | Pi(x, y, "padx"));+ for (int k = 0; k < 8; k++) TwinPatterns.Do(x, y, TwinPatterns.Act.MotionSet, 0 << 8 | k, k % 2);+ }+ var (a, ta) = SeqRig(120, rowsP, (x, y) => Rig(x, y, false));+ var (b, tb) = SeqRig(120, rowsP, (x, y) => Rig(x, y, true));+ using (a) using (b)+ {+ var still = Roll(a, 1.0);+ var played = Roll(b, 1.0);+ yield return (Diff(still, played) > 0.01 && Math.Abs(G(b, tb, "padx") - 0.5f) < 1e-6,+ "a motion lane on Pad X plays the pad's routes step by step and leaves the pad itself where it is");+ }+ }++ // Presets that play: the factory ones with the sequencer or the arpeggiator bring their pattern.+ {+ var cat = new FactoryPresetCatalog();+ var seqPresets = cat.All().Where(p => p.IsInstrument && p.BuiltinKind == 18 && cat.Document(p.Id)!.NamedParams!.TryGetValue("seq.on", out var on) && on > 0.5f).ToList();+ using var pe = new NotaEngine();+ int pt = pe.AddTwinTrack();+ var ms = seqPresets.First(p => p.DisplayName == "Morph Sequence");+ bool brings = cat.ApplyInPlace(pe, ms.Id, pt, -1) == ""+ && TwinPatterns.FromState(pe.GetPluginState(pt, -1))![0] is { Length: 8 } mp && mp.Lanes[0].Target == Pi(pe, pt, "lo.morph");+ yield return (seqPresets.Count >= 8 && brings, $"≥ 8 factory presets play the sequencer or the arpeggiator ({seqPresets.Count}), and a preset brings its pattern and motion lane");+ P(pe, pt, "lo.b.o2wave", 0.4f);+ var doc = PresetService.Capture(pe, pt, -1, "Mine")!;+ int pu = pe.AddTwinTrack();+ PresetService.ApplyInPlace(doc, pe, pu, -1);+ yield return (TwinPatterns.FromState(pe.GetPluginState(pu, -1))![0].Length == 8, "a user preset keeps the patterns");+ var mcp = new Nota.Mcp.Tools.TwinTools(pe, new SyncDispatch(), new NoRefresh());+ pe.ClearUndoHistory();+ string set = mcp.SetTwinPattern(pu, "C3 E3:100:50% | . | G3:80:tie | G3:80:30%", 3).Result;+ var got = mcp.GetTwinPattern(pu, 3).Result!;+ bool oneUndo = pe.Undo() && mcp.GetTwinPattern(pu, 3).Result!.Length == 16 && !pe.CanUndo;+ string bad = mcp.SetTwinPattern(pu, "C3 | H9").Result;+ yield return (set == "pattern 3: 4 steps" && got.Rows.SequenceEqual(new[] { "C3 E3:100:50%", ".", "G3:80:tie", "G3:80:30%" }) && got.SequencerOn+ && oneUndo && bad.StartsWith("error: row 2"),+ $"MCP set_twin_pattern / get_twin_pattern round-trip a pattern in one undo step ({set} | {bad})");+ }++ // "To clip": the pattern as a MIDI clip plays like the sequencer did.+ {+ var rowsC = new[] { "C3 G3:110:50%", ".", "E3:80:tie", "E3:80:40%", "A2:100:75%", ".", "G3:70:50%", "." };+ var (e, t) = SeqRig(120, rowsC, (x, y) => { P(x, y, "lo.a.o1level", 1f); P(x, y, "lo.a.noiselevel", 0f); P(x, y, "lo.a.ldcut", 0.6f); });+ var (f, u) = SeqRig(120, rowsC, (x, y) => { P(x, y, "lo.a.o1level", 1f); P(x, y, "lo.a.noiselevel", 0f); P(x, y, "lo.a.ldcut", 0.6f); });+ using (e) using (f)+ {+ var live = Roll(e, 1.0);+ f.ClearUndoHistory();+ int clip = TwinPatterns.ToClip(f, u, 0, 0.0);+ bool off = G(f, u, "seq.on") < 0.5f;+ var fromClip = Roll(f, 1.0);+ double d = Math.Abs(Db(Rms(live)) - Db(Rms(fromClip)));+ yield return (clip >= 0 && off && Diff(live, fromClip) == 0,+ $"SC-009: \"To clip\" writes the pattern as a clip that renders identically (maxdiff {Diff(live, fromClip):G3}, level {d:0.00} dB) and turns the sequencer off");+ yield return (f.Undo() && G(f, u, "seq.on") > 0.5f, "undoing \"To clip\" removes the clip and turns the sequencer back on");+ }+ }+ }++ // ---- fixes from the PR review (#406) -------------------------------------------------------+ private static IEnumerable<(bool, string)> ReviewChecks()+ {+ const int MorphDst = 1; // TwinMatrix's virtual destinations: None, Morph, …+ int Src(string name) => Array.IndexOf(TwinMatrix.Sources, name);++ // A queued pattern starts on its first step, whatever the length of the one before it;+ // picking the playing pattern again before the switch cancels it.+ (List<(int Pat, int Step, int Pend)> Log, NotaEngine E) Patterns(Action<NotaEngine, int, int> atBlock)+ {+ var (e, t) = SeqRig(120, Enumerable.Repeat("C4:100:25%", 16).ToArray());+ TwinPatterns.WritePattern(e, t, 1, Enumerable.Repeat("E4:100:25%", 24).ToArray());+ P(e, t, "seq.pattern", 0f);+ var log = new List<(int, int, int)>();+ var sc = new float[32];+ var tmp = new float[64 * 2];+ e.Seek(0); e.Play();+ for (int b = 0; b < Sr * 3 / 64; b++)+ {+ atBlock(e, t, b);+ e.RenderOffline(tmp, 64, Sr);+ e.InstrumentScope(t, sc);+ log.Add(((int)sc[1], (int)sc[0], (int)sc[2]));+ }+ return (log, e);+ }+ {+ var (log, e) = Patterns((x, y, b) => { if (b == 10) P(x, y, "seq.pattern", 1 / 7f); });+ using (e)+ {+ int first = log.FindIndex(l => l.Pat == 1);+ yield return (first > 0 && log[first].Step == 0,+ $"a queued pattern of another length starts on its first step (16 → 24 steps: step {(first > 0 ? log[first].Step + 1 : -1)})");+ }+ }+ {+ // Pattern 2 asked for while step 1 plays, the playing one picked back before step 3.+ var (log, e) = Patterns((x, y, b) => { if (b == 10) P(x, y, "seq.pattern", 1 / 7f); if (b == 150) P(x, y, "seq.pattern", 0f); });+ using (e)+ yield return (log[140].Pend == 1 && log.All(l => l.Pat == 0) && log[^1].Pend == -1,+ "picking the playing pattern again cancels the queued one");+ }++ // The arpeggiator drops the pattern's motion: a motion lane on the cutoff stops overriding the knob.+ {+ var (e, t) = SeqRig(120, Enumerable.Repeat("C4:100:90%", 16).ToArray(), (x, y) => { P(x, y, "lo.a.noiselevel", 0f); P(x, y, "lo.a.o1level", 1f); });+ using (e)+ {+ TwinPatterns.Do(e, t, TwinPatterns.Act.MotionTarget, Pi(e, t, "lo.a.ldcut"));+ for (int k = 0; k < 16; k++) TwinPatterns.Do(e, t, TwinPatterns.Act.MotionSet, k, 0f); // the lane closes the filter+ P(e, t, "lo.a.ldcut", 1f);+ var tmp = new float[512 * 2];+ e.Seek(0); e.Play();+ for (int b = 0; b < 20; b++) e.RenderOffline(tmp, 512, Sr);+ P(e, t, "seq.kind", 1f); // to the arpeggiator, a held chord+ e.TrackNoteOn(t, 60, 0.8f);+ Roll2(e, Sr / 2);+ double open = Rms(Roll2(e, Sr / 2));+ yield return (Db(open) > -40, $"switching to the arpeggiator drops the pattern's motion lane (open cutoff: {Db(open):0} dB)");+ }+ }+ float[] Roll2(NotaEngine e, int frames) { var o = new float[frames * 2]; var tmp = new float[512 * 2]; for (int d = 0; d < frames;) { int m = Math.Min(512, frames - d); e.RenderOffline(tmp, m, Sr); Array.Copy(tmp, 0, o, d * 2, m * 2); d += m; } return o; }++ // A held chord follows Pan (it used to keep its note-on pan).+ {+ using var e = new NotaEngine();+ int t = e.AddTwinTrack();+ P(e, t, "lo.a.drift", 0f); P(e, t, "lo.a.spread", 0f);+ Render(e, 512);+ e.TrackNoteOn(t, 60, 0.8f);+ var before = Render(e, Sr / 4);+ P(e, t, "lo.pan", 0f); // hard left+ Render(e, Sr / 10);+ var after = Render(e, Sr / 4);+ double balBefore = Db(Ch(before, 0)) - Db(Ch(before, 1)), balAfter = Db(Ch(after, 0)) - Db(Ch(after, 1));+ yield return (Math.Abs(balBefore) < 1 && balAfter > 20, $"a held note follows Pan (L − R: {balBefore:0.0} dB, then {balAfter:0} dB)");+ }++ // Osc 2 Low leaves the keyboard: the same pitch for C3 and C5.+ {+ double Hz(int note)+ {+ using var e = new NotaEngine();+ int t = e.AddTwinTrack();+ foreach (var (id, v) in new[] { ("lo.a.o1level", 0f), ("lo.a.o2level", 1f), ("lo.a.o2lo", 1f), ("lo.a.o2coarse", 1f), ("lo.a.ldcut", 1f), ("lo.a.drift", 0f) })+ P(e, t, id, v);+ Render(e, 512);+ e.TrackNoteOn(t, note, 0.8f);+ var st = Render(e, Sr);+ double best = 0, bestHz = 0;+ for (double hz = 20; hz < 400; hz += 0.5) { double a = At(st, hz, Sr / 4); if (a > best) { best = a; bestHz = hz; } }+ return bestHz;+ }+ double lo = Hz(48), hi = Hz(72);+ yield return (lo > 0 && Math.Abs(lo - hi) < 1.5, $"Osc 2 Low ignores the key: C3 and C5 both at {lo:0.0} / {hi:0.0} Hz");+ }++ // LFO 3's Symmetry and Curve reach the sound (a route from LFO 3 to the cutoff).+ {+ double Lfo3(float sym, float curve)+ {+ using var e = new NotaEngine();+ int t = e.AddTwinTrack();+ foreach (var (id, v) in new[] { ("lo.a.lfo3shape", 0.2f), ("lo.a.lfo3sym", sym), ("lo.a.lfo3curve", curve), ("lo.a.lfo3rate", 0.5f), ("lo.a.ldcut", 0.5f), ("lo.a.drift", 0f) })+ P(e, t, id, v);+ TwinMatrix.Add(e, t, Src("LFO 3"), TwinMatrix.DestinationOfSide("ldcut"), 0.8f, 0.8f);+ Render(e, 512);+ e.TrackNoteOn(t, 48, 0.8f);+ return Rms(Render(e, Sr));+ }+ double plain = Lfo3(0.5f, 0.5f), skew = Lfo3(0.95f, 0.5f), bent = Lfo3(0.5f, 1f);+ yield return (Math.Abs(Db(skew) - Db(plain)) > 0.1 && Math.Abs(Db(bent) - Db(plain)) > 0.1,+ $"LFO 3's Symmetry and Curve change the sound ({Db(plain):0.00} / {Db(skew):0.00} / {Db(bent):0.00} dB)");+ }++ // Seq gate is a live source: routed to the oscillator level, it opens the sound while steps play.+ {+ double Gated(bool route)+ {+ var (e, t) = SeqRig(120, Enumerable.Repeat("C4:100:90%", 16).ToArray(), (x, y) => { P(x, y, "lo.a.noiselevel", 0f); P(x, y, "lo.a.o1level", 0f); });+ using (e)+ {+ if (route) TwinMatrix.Add(e, t, Src("Seq gate"), TwinMatrix.DestinationOfSide("o1level"), 1f, 1f);+ return Rms(Roll(e, 1.0));+ }+ }+ double off = Gated(false), on = Gated(true);+ yield return (Db(on) - Db(off) > 20, $"the Seq gate source moves its destination ({Db(off):0} dB without the route, {Db(on):0} dB with it)");+ }++ // A route that lives only on side B starts when a per-note Morph route takes the note to B.+ {+ double Note(bool bOnly)+ {+ using var e = new NotaEngine();+ int t = e.AddTwinTrack();+ P(e, t, "lo.morph", 0f); P(e, t, "lo.a.drift", 0f);+ TwinMatrix.Add(e, t, Src("Velocity"), MorphDst, 1f, 1f);+ if (bOnly) TwinMatrix.Add(e, t, Src("Velocity"), TwinMatrix.DestinationOfSide("o1level"), 0f, -1f);+ Render(e, 512);+ e.TrackNoteOn(t, 60, 1f);+ return Rms(Render(e, Sr / 2));+ }+ double plain = Note(false), withB = Note(true);+ yield return (Db(plain) - Db(withB) > 20,+ $"a side-B-only route acts once the note morphs to B ({Db(plain):0} dB, {Db(withB):0} dB with the B route closing Osc 1)");+ }++ // Release velocity survives the sustain pedal.+ {+ double Pedal(float relVel)+ {+ using var e = new NotaEngine();+ int t = e.AddTwinTrack();+ P(e, t, "lo.a.aenvr", 0.25f);+ TwinMatrix.Add(e, t, Src("Release velocity"), TwinMatrix.DestinationOfSide("aenvr"), 1f, 1f);+ Render(e, 512);+ e.TrackNoteOn(t, 60, 0.8f);+ e.SendTrackController(t, 64, 1f);+ Render(e, Sr / 4);+ e.TrackNoteOffVelocity(t, 60, relVel);+ Render(e, Sr / 10);+ e.SendTrackController(t, 64, 0f);+ Render(e, Sr / 10);+ return Rms(Render(e, Sr / 2));+ }+ double soft = Pedal(0.05f), hard = Pedal(1f);+ yield return (Db(hard) - Db(soft) > 6, $"release velocity is kept while the pedal holds the note ({Db(soft):0} / {Db(hard):0} dB)");+ }++ // A preset's patterns undo with the preset.+ {+ using var e = new NotaEngine();+ int t = e.AddTwinTrack(), src = e.AddTwinTrack();+ TwinPatterns.WritePattern(e, src, 0, new[] { "C3", "E3", "G3" });+ var doc = PresetService.Capture(e, src, -1, "Seq")!;+ e.ClearUndoHistory();+ PresetEdit.Apply(e, t, PresetSurface.Instrument, -1, "", "Seq", () => PresetService.ApplyInPlace(doc, e, t, -1));+ bool applied = TwinPatterns.FromState(e.GetPluginState(t, -1))![0].Length == 3;+ bool undone = e.Undo() && TwinPatterns.FromState(e.GetPluginState(t, -1))![0].Length == 16 && !e.CanUndo;+ yield return (applied && undone, "undoing a Twin preset brings the old patterns back with the old sound, in one step");+ }++ // On an Instrument Rack chain: the card's state reads the chain's Twin, and pattern edits undo.+ {+ using var e = new NotaEngine();+ int r = e.AddInstrumentRackTrack();+ e.RackAddChain(r, 18);+ var px = RackChainEngineProxy.Create(e, 0);+ e.ClearUndoHistory();+ TwinPatterns.Do(px, r, TwinPatterns.Act.AddStepNote, 2 << 8 | 64, 0.7f);+ var read = TwinPatterns.FromState(px.GetPluginState(r, -1));+ bool reads = read is not null && read[0].Steps[2].Notes.SequenceEqual(new[] { 64 });+ bool undone = e.Undo() && TwinPatterns.FromState(px.GetPluginState(r, -1))![0].Steps[2].IsRest;+ yield return (reads && undone, "a Twin on a rack chain: its patterns read through the chain, and a pattern edit is an undo step");+ }++ // A filter whose sources move away fades out what it holds instead of stopping dead.+ {+ using var e = new NotaEngine();+ int t = e.AddTwinTrack();+ foreach (var (id, v) in new[] { ("lo.a.drift", 0f), ("lo.a.o1bal", 1f), ("lo.a.route", 1f), ("lo.a.ldcut", 0.33f), ("lo.a.ldres", 0.45f),+ ("lo.a.ldenv", 0.5f), ("lo.a.mmcut", 0f), ("lo.a.aenvr", 0.6f) })+ P(e, t, id, v);+ Render(e, 512);+ e.TrackNoteOn(t, 48, 0.8f);+ Render(e, Sr / 4, 32);+ double before = Rms(Render(e, 256, 32));+ P(e, t, "lo.a.o1bal", 0f); // every source to the (closed) multimode: the ladder is unfed+ Render(e, 32, 32);+ double just = Rms(Render(e, 96, 32));+ double later = Rms(Render(e, Sr / 10, 32), Sr / 10 - 512);+ yield return (Db(just) - Db(before) > -15 && Db(later) < Db(just) - 15, // later: only the closed multimode's leak+ $"an unfed ladder fades what it holds ({Db(before):0} → {Db(just):0} dB just after, {Db(later):0} dB later)");+ }++ // Back to Single: Upper's held notes release instead of stopping dead.+ {+ using var e = new NotaEngine();+ int t = e.AddTwinTrack();+ P(e, t, "mode", 0.5f); P(e, t, "lo.vol", 0f); P(e, t, "up.a.aenvr", 0.75f); P(e, t, "up.b.aenvr", 0.75f);+ Render(e, 512);+ e.TrackNoteOn(t, 60, 0.8f);+ Render(e, Sr / 4);+ e.TrackNoteOff(t, 60);+ P(e, t, "mode", 0f);+ Render(e, 1024);+ double tail = Rms(Render(e, Sr / 10));+ yield return (Db(tail) > -50, $"switching Layer to Single lets Upper's notes ring out ({Db(tail):0} dB 25 ms on)");+ }++ // A whole 64-step pattern written in one go undoes in one step, and the history before it stays.+ {+ using var e = new NotaEngine();+ int t = e.AddTwinTrack();+ e.ClearUndoHistory();+ TwinPatterns.Do(e, t, TwinPatterns.Act.AddStepNote, 0 << 8 | 60, 0.8f);+ TwinPatterns.WritePattern(e, t, 0, Enumerable.Range(0, 64).Select(i => i % 2 == 0 ? "C3 E3:100:50%" : "G3:90:40%").ToArray());+ bool written = TwinPatterns.FromState(e.GetPluginState(t, -1))![0].Length == 64;+ bool back = e.Undo() && TwinPatterns.FromState(e.GetPluginState(t, -1))![0] is { Length: 16 } p1 && p1.Steps[0].Notes.SequenceEqual(new[] { 60 });+ bool first = e.Undo() && TwinPatterns.FromState(e.GetPluginState(t, -1))![0].Steps[0].IsRest;+ yield return (written && back && first, "writing a 64-step pattern is one undo step, and the edit before it still undoes");+ }++ // On a rack chain: a side copy undoes (the chain's params have no undo target of their own),+ // and To clip refuses (the clip would play every chain).+ {+ using var e = new NotaEngine();+ int r = e.AddInstrumentRackTrack();+ e.RackAddChain(r, 18);+ var px = RackChainEngineProxy.Create(e, 0);+ P(px, r, "lo.a.ldcut", 0.2f); P(px, r, "lo.b.ldcut", 0.8f);+ e.ClearUndoHistory();+ TwinSides.Apply(px, r, TwinSides.Edit.CopyAToB);+ bool copied = Math.Abs(G(px, r, "lo.b.ldcut") - 0.2f) < 1e-6;+ bool undone = e.Undo() && Math.Abs(G(px, r, "lo.b.ldcut") - 0.8f) < 1e-6;+ bool refused = TwinPatterns.ToClipBlock(px, r, 0) == TwinPatterns.ClipBlock.InRack && TwinPatterns.ToClip(px, r, 0, 0) == -1;+ yield return (copied && undone && refused, "a Twin on a rack chain: A → B undoes, To clip refuses");+ }++ // To clip: an empty motion step plays the knob, as the sequencer does.+ {+ using var e = new NotaEngine();+ int t = e.AddTwinTrack();+ TwinPatterns.WritePattern(e, t, 0, new[] { "C3", "E3", "G3", "C4" });+ int pid = Pi(e, t, "lo.a.ldcut");+ P(e, t, "lo.a.ldcut", 0.6f);+ TwinPatterns.Do(e, t, TwinPatterns.Act.MotionTarget, pid);+ TwinPatterns.Do(e, t, TwinPatterns.Act.MotionSet, 0, 0.1f);+ TwinPatterns.Do(e, t, TwinPatterns.Act.MotionSet, 2, 0.9f);+ TwinPatterns.ToClip(e, t, 0, 0);+ var pts = e.GetAutomationPoints(t, e.AddPluginAutomationLane(t, -1, "lo.a.ldcut"));+ bool knob = pts.Any(p => Math.Abs(p.Beat - 0.25) < 1e-9 && Math.Abs(p.Value - 0.6f) < 1e-4);+ yield return (knob, $"To clip holds the knob's value on an empty motion step ({pts.Length} points)");+ }++ // Transport stopped: a held key runs the sequencer on its own clock (Seq from step 1, Arp over+ // the held chord); the last key up stops it, Latch / Hold keeps it going.+ foreach (bool arp in new[] { false, true })+ {+ var (e, t) = SeqRig(120, Enumerable.Repeat("C4:100:25%", 16).ToArray(),+ (x, y) => { P(x, y, "lo.a.noiselevel", 0f); P(x, y, "lo.a.o1level", 1f); P(x, y, "lo.a.o1wave", 1f); if (arp) P(x, y, "seq.kind", 1f); });+ using (e)+ {+ Render(e, 512);+ double idle = Rms(Render(e, Sr / 2));+ foreach (var n in arp ? new[] { 60, 64, 67 } : new[] { 62 }) e.TrackNoteOn(t, n, 0.8f);+ int steps = Onsets(Render(e, Sr)).Count; // 1 s at 120 BPM: 8 sixteenths+ foreach (var n in arp ? new[] { 60, 64, 67 } : new[] { 62 }) e.TrackNoteOff(t, n);+ Render(e, Sr / 4);+ double after = Rms(Render(e, Sr / 2));+ P(e, t, arp ? "arp.hold" : "seq.latch", 1f);+ e.TrackNoteOn(t, 62, 0.8f); Render(e, Sr / 4); e.TrackNoteOff(t, 62);+ int latched = Onsets(Render(e, Sr)).Count;+ yield return (idle < 1e-6 && steps >= 7 && after < 1e-5 && latched >= 7,+ $"transport stopped: a held key runs the {(arp ? "arpeggiator" : "sequencer")} ({steps} steps in 1 s), letting go stops it, {(arp ? "Hold" : "Latch")} keeps it ({latched})");+ }+ }++ // Latch switched off with no key down stops a key-run pattern; a key the sequencer didn't+ // take releases normally even while a transpose key is still held.+ {+ var (e, t) = SeqRig(120, Enumerable.Repeat("C4:100:25%", 16).ToArray(),+ (x, y) => { P(x, y, "lo.a.noiselevel", 0f); P(x, y, "lo.a.o1level", 1f); P(x, y, "seq.latch", 1f); });+ using (e)+ {+ Render(e, 512);+ e.TrackNoteOn(t, 62, 0.8f); Render(e, Sr / 4); e.TrackNoteOff(t, 62);+ int latched = Onsets(Render(e, Sr / 2)).Count;+ P(e, t, "seq.latch", 0f);+ Render(e, Sr / 4);+ double stopped = Rms(Render(e, Sr / 2));+ P(e, t, "seq.latch", 1f);+ e.TrackNoteOn(t, 62, 0.8f); Render(e, Sr / 8); // a transpose key held…+ P(e, t, "seq.on", 0f); Render(e, Sr / 8);+ e.TrackNoteOn(t, 60, 0.8f); Render(e, Sr / 8); // …then another key, the sequencer off+ e.TrackNoteOff(t, 60);+ Render(e, Sr / 2);+ double after = Rms(Render(e, Sr / 4));+ yield return (latched >= 3 && stopped < 1e-5 && after < 1e-5,+ $"Latch off stops a key-run pattern ({Db(stopped):0} dB), and a key the sequencer didn't take releases ({Db(after):0} dB)");+ }+ }++ // A per-note route to a part's effect follows the newest note: Velocity → Reverb Mix.+ {+ double Tail(float vel)+ {+ using var e = new NotaEngine();+ int t = e.AddTwinTrack();+ foreach (var (id, v) in new[] { ("lo.a.revon", 1f), ("lo.a.revmix", 0f), ("lo.a.revsize", 0.9f), ("lo.a.aenvr", 0.1f) })+ P(e, t, id, v);+ TwinMatrix.Add(e, t, Src("Velocity"), TwinMatrix.DestinationOfSide("revmix"), 1f, 1f);+ Render(e, 512);+ e.TrackNoteOn(t, 60, vel);+ Render(e, Sr / 2);+ e.TrackNoteOff(t, 60);+ Render(e, Sr / 4);+ return Rms(Render(e, Sr / 2));+ }+ double soft = Tail(0.05f), hard = Tail(1f);+ yield return (Db(hard) - Db(soft) > 6, $"a per-note route reaches the part's effect: Velocity → Reverb Mix ({Db(soft):0} / {Db(hard):0} dB tail)");+ }++ // To clip: refuses what a clip can't play as the sequencer does; keeps automation outside the clip;+ // a stepped lane holds each value up to the next (swung) step, a smooth one glides on to the first.+ {+ using var e = new NotaEngine();+ int t = e.AddTwinTrack();+ TwinPatterns.WritePattern(e, t, 0, new[] { "C3", "E3", "G3", "C4" });+ P(e, t, "mode", 0.5f); P(e, t, "seq.target", 0.5f); // Layer, the sequencer on Upper+ bool refused = TwinPatterns.ToClipBlock(e, t, 0) == TwinPatterns.ClipBlock.LayerOnePart && TwinPatterns.ToClip(e, t, 0, 0) == -1;+ P(e, t, "mode", 0f);+ int pid = Pi(e, t, "lo.a.ldcut");+ int li = e.AddPluginAutomationLane(t, -1, "lo.a.ldcut");+ e.SetAutomationPoints(t, li, new[] { new AutomationPoint(32, 0.2f), new AutomationPoint(36, 0.9f) });+ TwinPatterns.Do(e, t, TwinPatterns.Act.MotionTarget, pid);+ for (int k = 0; k < 4; k++) TwinPatterns.Do(e, t, TwinPatterns.Act.MotionSet, k, k / 3f);+ P(e, t, "seq.swing", 1f);+ int clip = TwinPatterns.ToClip(e, t, 0, 0);+ var pts = e.GetAutomationPoints(t, li);+ bool kept = pts.Any(p => p.Beat == 32 && Math.Abs(p.Value - 0.2f) < 1e-6) && pts.Any(p => p.Beat == 36);+ bool ordered = pts.Zip(pts.Skip(1)).All(z => z.First.Beat <= z.Second.Beat);+ // Step 1 (odd) is swung late by half a step: step 0's value holds until just before it.+ double sb = 0.25, on1 = sb + 0.5 * sb;+ bool held = pts.Any(p => Math.Abs(p.Beat - (on1 - 1e-4)) < 1e-6 && p.Value == 0f) && !pts.Any(p => p.Beat > sb * 0.999 && p.Beat < on1 - 1e-3 && p.Value != 0f);+ yield return (refused && clip >= 0 && kept && ordered && held,+ $"To clip refuses a Layer pattern on one part, keeps the lane's other points and holds stepped motion to the swung next step ({pts.Length} points)");+ }+ }++ private static double Diff(float[] x, float[] y) { double d = 0; for (int i = 0; i < Math.Min(x.Length, y.Length); i++) d = Math.Max(d, Math.Abs(x[i] - y[i])); return d; }++ // How far apart two onset lists are (the largest gap between matched onsets, in samples).+ private static int Diff2(List<int> a, List<int> b)+ {+ if (a.Count != b.Count) return int.MaxValue;+ int w = 0;+ for (int i = 0; i < a.Count; i++) w = Math.Max(w, Math.Abs(a[i] - b[i]));+ return w;+ }+}diff --git a/tests/perf/nota_perf.cpp b/tests/perf/nota_perf.cppindex d7a007f2..43d8ac86 100644--- a/tests/perf/nota_perf.cpp+++ b/tests/perf/nota_perf.cpp@@ -98,6 +98,27 @@ void fillChords6(NotaEngine* e, int track, int transpose, double startBeat, doubnota_clip_set_notes(e, track, clip, notes.data(), (int)notes.size());}+// Sets a track instrument's param by id (no-op for an unknown id).+void setParamById(NotaEngine* e, int track, const char* id, float v) {+ const int n = nota_plugin_param_count(e, track, -1);+ for (int i = 0; i < n; ++i) {+ const char* pid = nota_plugin_param_id(e, track, -1, i);+ if (pid && std::strcmp(pid, id) == 0) {+ nota_plugin_param_set(e, track, -1, i, v);+ return;+ }+ }+}++// A held `voices`-note chord for 4 bars, retriggered every bar: a synth at full polyphony.+void fillFullChord(NotaEngine* e, int track, int voices) {+ const int clip = nota_track_add_midi_clip(e, track, 0.0, 16.0);+ std::vector<NotaNoteData> notes;+ for (int bar = 0; bar < 4; ++bar)+ for (int k = 0; k < voices; ++k) notes.push_back({36 + k * 4 + (bar & 1), bar * 4.0, 3.9, 0.75f, 0});+ nota_clip_set_notes(e, track, clip, notes.data(), (int)notes.size());+}+// An 8 s stereo 48 kHz WAV of a chord with a little noise (so the stretch has real work), in// the temp dir; the warp scenarios load it.// Each process writes its own file (perf-gate runs scenarios in parallel), removed once@@ -159,6 +180,7 @@ std::string instrumentName(int kind) {case 15: return "Consort";case 16: return "Keys";case 17: return "Mosaic (no program)";+ case 18: return "Twin";default: return "Instrument kind " + std::to_string(kind);}}@@ -197,6 +219,10 @@ std::vector<Scenario> scenarios() {s.push_back({"instrument-rack", "Instrument Rack, 2 Synth chains"});s.push_back({"effect-base", "Synth alone (effect baseline)"});s.push_back({"aurora-supersaw-2x", "Aurora Super Saw x2"});+ // Full-polyphony synth loads (specs/055 SC-001: Twin at 12 voices against Pentad at 16).+ s.push_back({"pentad-full-16", "Pentad, 16-voice chord"});+ s.push_back({"twin-full-12", "Twin, 12-voice chord, both filters, 16 routes, FX"});+ s.push_back({"twin-layer-6x6", "Twin Layer, 6 + 6 voices, both parts' FX"});for (int k = 0; k < kMaxKind; ++k) {const std::string name = effectName(k);if (name.empty()) continue;@@ -267,6 +293,55 @@ bool build(NotaEngine* e, const std::string& id) {}return true;}+ if (id == "pentad-full-16") {+ const int t = instrumentTrack(e, 14);+ if (t < 0) return false;+ setParamById(e, t, "polyphony", 1.0f); // 16 voices+ fillFullChord(e, t, 16);+ return true;+ }+ if (id == "twin-full-12") {+ // Both oscillators and noise into both filters, half series / half parallel, resonant.+ // and the part's effects on: chorus, delay and reverb.+ const int t = instrumentTrack(e, 18);+ if (t < 0) return false;+ for (auto [pid, v] : {std::pair{"lo.a.o2level", 0.8f}, {"lo.a.noiselevel", 0.2f}, {"lo.a.o1bal", 0.5f},+ {"lo.a.o2bal", 0.5f}, {"lo.a.route", 0.5f}, {"lo.a.mmres", 0.4f}, {"lo.a.ldres", 0.4f},+ {"lo.a.o1metal", 0.3f}, {"lo.a.drive", 0.3f}, {"lo.a.brute", 0.3f}, {"lo.a.modfxon", 1.0f},+ {"lo.a.dlyon", 1.0f}, {"lo.a.revon", 1.0f}})+ setParamById(e, t, pid, v);+ // 16 live matrix routes (slots 7..22; 1..6 are Init's expression routes, idle here): LFOs,+ // envelopes, velocity, key and random onto cutoffs, wave, width, morph and more.+ setParamById(e, t, "lo.m7.src", 1.0f / 63.0f); setParamById(e, t, "lo.m7.dst", 28.0f / 255.0f); setParamById(e, t, "lo.a.m7amt", 0.6f); setParamById(e, t, "lo.b.m7amt", 0.6f);+ setParamById(e, t, "lo.m8.src", 2.0f / 63.0f); setParamById(e, t, "lo.m8.dst", 23.0f / 255.0f); setParamById(e, t, "lo.a.m8amt", 0.6f); setParamById(e, t, "lo.b.m8amt", 0.6f);+ setParamById(e, t, "lo.m9.src", 3.0f / 63.0f); setParamById(e, t, "lo.m9.dst", 6.0f / 255.0f); setParamById(e, t, "lo.a.m9amt", 0.6f); setParamById(e, t, "lo.b.m9amt", 0.6f);+ setParamById(e, t, "lo.m10.src", 4.0f / 63.0f); setParamById(e, t, "lo.m10.dst", 13.0f / 255.0f); setParamById(e, t, "lo.a.m10amt", 0.6f); setParamById(e, t, "lo.b.m10amt", 0.6f);+ setParamById(e, t, "lo.m11.src", 6.0f / 63.0f); setParamById(e, t, "lo.m11.dst", 1.0f / 255.0f); setParamById(e, t, "lo.a.m11amt", 0.6f); setParamById(e, t, "lo.b.m11amt", 0.6f);+ setParamById(e, t, "lo.m12.src", 7.0f / 63.0f); setParamById(e, t, "lo.m12.dst", 33.0f / 255.0f); setParamById(e, t, "lo.a.m12amt", 0.6f); setParamById(e, t, "lo.b.m12amt", 0.6f);+ setParamById(e, t, "lo.m13.src", 9.0f / 63.0f); setParamById(e, t, "lo.m13.dst", 29.0f / 255.0f); setParamById(e, t, "lo.a.m13amt", 0.6f); setParamById(e, t, "lo.b.m13amt", 0.6f);+ setParamById(e, t, "lo.m14.src", 18.0f / 63.0f); setParamById(e, t, "lo.m14.dst", 15.0f / 255.0f); setParamById(e, t, "lo.a.m14amt", 0.6f); setParamById(e, t, "lo.b.m14amt", 0.6f);+ setParamById(e, t, "lo.m15.src", 1.0f / 63.0f); setParamById(e, t, "lo.m15.dst", 67.0f / 255.0f); setParamById(e, t, "lo.a.m15amt", 0.6f); setParamById(e, t, "lo.b.m15amt", 0.6f);+ setParamById(e, t, "lo.m16.src", 2.0f / 63.0f); setParamById(e, t, "lo.m16.dst", 34.0f / 255.0f); setParamById(e, t, "lo.a.m16amt", 0.6f); setParamById(e, t, "lo.b.m16amt", 0.6f);+ setParamById(e, t, "lo.m17.src", 3.0f / 63.0f); setParamById(e, t, "lo.m17.dst", 24.0f / 255.0f); setParamById(e, t, "lo.a.m17amt", 0.6f); setParamById(e, t, "lo.b.m17amt", 0.6f);+ setParamById(e, t, "lo.m18.src", 5.0f / 63.0f); setParamById(e, t, "lo.m18.dst", 20.0f / 255.0f); setParamById(e, t, "lo.a.m18amt", 0.6f); setParamById(e, t, "lo.b.m18amt", 0.6f);+ setParamById(e, t, "lo.m19.src", 6.0f / 63.0f); setParamById(e, t, "lo.m19.dst", 8.0f / 255.0f); setParamById(e, t, "lo.a.m19amt", 0.6f); setParamById(e, t, "lo.b.m19amt", 0.6f);+ setParamById(e, t, "lo.m20.src", 2.0f / 63.0f); setParamById(e, t, "lo.m20.dst", 32.0f / 255.0f); setParamById(e, t, "lo.a.m20amt", 0.6f); setParamById(e, t, "lo.b.m20amt", 0.6f);+ setParamById(e, t, "lo.m21.src", 1.0f / 63.0f); setParamById(e, t, "lo.m21.dst", 16.0f / 255.0f); setParamById(e, t, "lo.a.m21amt", 0.6f); setParamById(e, t, "lo.b.m21amt", 0.6f);+ setParamById(e, t, "lo.m22.src", 4.0f / 63.0f); setParamById(e, t, "lo.m22.dst", 25.0f / 255.0f); setParamById(e, t, "lo.a.m22amt", 0.6f); setParamById(e, t, "lo.b.m22amt", 0.6f);+ fillFullChord(e, t, 12);+ return true;+ }+ if (id == "twin-layer-6x6") {+ // Layer with the voices shared 6 + 6: a 6-note chord sounds on both parts (SC-010).+ const int t = instrumentTrack(e, 18);+ if (t < 0) return false;+ for (auto [pid, v] : {std::pair{"mode", 0.5f}, {"share", 0.5f}, {"lo.a.o2level", 0.8f}, {"up.a.o2level", 0.8f},+ {"lo.a.o1bal", 0.5f}, {"up.a.o1bal", 0.5f}, {"lo.a.route", 0.5f}, {"up.a.route", 0.5f},+ {"lo.a.modfxon", 1.0f}, {"lo.a.revon", 1.0f}, {"up.a.dlyon", 1.0f}, {"up.a.revon", 1.0f}})+ setParamById(e, t, pid, v);+ fillFullChord(e, t, 6);+ return true;+ }if (id == "audio-tails-8") {const std::string wav = warpTestWav();bool ok = true;