nooise 1.8.2

Ambient music generator for the terminal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet};
use std::f32::consts::TAU;
use std::fmt;

use super::{
    ControlSpec, FluidControls, LfoSnap, MACRO_CONTROLS, MACRO_COUNT, TimingContext,
    beat_grid_adjust, beat_grid_ratio, beat_grid_snap, is_macro_id, nearest_power_of_two,
    normalize_unit_input, ordered_step_ratio, snap_step, spec_by_id, unit_key,
};

pub(crate) const DEFAULT_LFO_CYCLE_BEATS: f32 = 2.0;
pub(crate) const DEFAULT_LFO_DEPTH_RATIO: f32 = 0.0;
pub(crate) const MIN_LFO_CYCLE_BEATS: f32 = 0.125;
pub(crate) const MAX_LFO_CYCLE_BEATS: f32 = 64.0;
pub(crate) const MAX_LFO_OFFSET_BEATS: f32 = 4.0;

/// Upper bound on a `Steps` shape's custom automation sequence. Fixed so
/// `LfoRoute` stays `Copy` (a `[f32; MAX_LFO_STEPS]` array, no allocation on
/// the audio thread).
pub(crate) const MAX_LFO_STEPS: usize = 16;
pub(crate) const DEFAULT_LFO_STEP_COUNT: u8 = 4;
/// Default edge-glide: a slight slide into each step so the staircase doesn't
/// click on a live-read control (see `step_value_at`). 0 = hard steps.
pub(crate) const DEFAULT_LFO_STEP_GLIDE: f32 = 0.15;
/// Default `Steps` pattern: three neutral steps then a full up-step, so a
/// fresh Steps shape reads as a rhythmic accent on the last beat.
const DEFAULT_LFO_STEPS: [f32; MAX_LFO_STEPS] = {
    let mut steps = [0.0f32; MAX_LFO_STEPS];
    steps[3] = 1.0;
    steps
};

const AMOUNT_STEP: f32 = 0.01;
const INTERVAL_STEP: f32 = 0.125;
const OFFSET_STEP: f32 = 0.125;
const STEP_VALUE_STEP: f32 = 0.05;
const STEP_GLIDE_STEP: f32 = 0.05;

/// Softness of the smoothed square edge; higher = closer to a hard square.
const SQUARE_SMOOTH: f32 = 6.0;

/// Fraction of a ramp's cycle, right before it wraps, eased toward the next
/// cycle's start value instead of jumping there in a single sample. Every
/// other shape is continuous at the wrap already (sine and triangle by
/// construction, square via SQUARE_SMOOTH); a bare ramp is a sawtooth with a
/// full-swing discontinuity every cycle, which clicks when applied straight
/// to a live-read control like level or cutoff.
const RAMP_WRAP_EASE: f32 = 0.02;
const PICKUP_SCAN_STEP_BEATS: f64 = 1.0 / 256.0;
const PICKUP_CROSSING_EPSILON: f32 = 1e-4;

// Envelope route field ranges. Attack/decay reach into the minutes at slow
// tempos (512 beats is ~6 min at 82 BPM, ~12 min at 40 BPM) so the same
// one-shot serves both fast swells and set-and-forget macro blooms.
pub(crate) const MAX_ENV_ATTACK_BEATS: f32 = 512.0;
pub(crate) const MAX_ENV_DECAY_BEATS: f32 = 512.0;
const ENV_BEATS_STEP: f32 = 0.5;
const ENV_AMOUNT_STEP: f32 = 0.01;
const DEFAULT_ENV_ATTACK_BEATS: f32 = 1.0;
const DEFAULT_ENV_DECAY_BEATS: f32 = 4.0;

#[derive(Clone, Copy)]
pub(crate) struct ControlAddress {
    spec: &'static ControlSpec,
}

impl ControlAddress {
    pub(crate) fn new(id: &'static str) -> Self {
        let spec = spec_by_id(id).expect("control address must reference a registered control");
        Self { spec }
    }

    pub(crate) fn id(self) -> &'static str {
        self.spec.id
    }

    pub(crate) fn spec(self) -> &'static ControlSpec {
        self.spec
    }
}

impl fmt::Debug for ControlAddress {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("ControlAddress").field(&self.id()).finish()
    }
}

impl PartialEq for ControlAddress {
    fn eq(&self, other: &Self) -> bool {
        self.id() == other.id()
    }
}

impl Eq for ControlAddress {}

impl Ord for ControlAddress {
    fn cmp(&self, other: &Self) -> Ordering {
        self.id().cmp(other.id())
    }
}

impl PartialOrd for ControlAddress {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// Which modulator editor is currently open on a control. LFO, envelope, and
/// macro routes are independent siblings that can all live on one control
/// (envelopes only on macro sliders, macro routes only on regular controls).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ModKind {
    Lfo,
    Envelope,
    Macro,
}

/// Sampling context shared by every modulator so the UI marker and the engine
/// value come from the same math. `kick_*` describe the live kick grid, which
/// the on-kick envelope trigger reconstructs deterministically.
#[derive(Clone, Copy, Debug)]
pub(crate) struct ModContext {
    pub(crate) beat: f64,
    pub(crate) kick_interval_beats: f32,
    pub(crate) kick_offset_beats: f32,
}

impl ModContext {
    /// Context for an LFO-only evaluation; the kick fields are unused because
    /// no LFO shape depends on the kick grid.
    #[cfg(test)]
    pub(crate) fn lfo_only(beat: f64) -> Self {
        Self {
            beat,
            kick_interval_beats: 1.0,
            kick_offset_beats: 0.0,
        }
    }
}

// ============================================================
// LFO shapes
// ============================================================

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum LfoShape {
    Sine,
    Triangle,
    RampUp,
    RampDown,
    Square,
    RandomDrift,
    SampleHold,
    /// User-drawn staircase: a per-cycle sequence of `step_count` bipolar
    /// values on `LfoRoute`, edited in the Shape row's inline step submenu.
    Steps,
}

impl LfoShape {
    pub(crate) const ALL: [LfoShape; 8] = [
        Self::Sine,
        Self::Triangle,
        Self::RampUp,
        Self::RampDown,
        Self::Square,
        Self::RandomDrift,
        Self::SampleHold,
        Self::Steps,
    ];

    pub(crate) fn label(self) -> &'static str {
        match self {
            Self::Sine => "sine",
            Self::Triangle => "triangle",
            Self::RampUp => "ramp up",
            Self::RampDown => "ramp down",
            Self::Square => "square",
            Self::RandomDrift => "random drift",
            Self::SampleHold => "sample & hold",
            Self::Steps => "steps",
        }
    }

    /// Random shapes generate their trajectory from the route seed instead of a
    /// fixed periodic curve, so the animated lane must scope them differently.
    pub(crate) fn is_random(self) -> bool {
        matches!(self, Self::RandomDrift | Self::SampleHold)
    }

    fn index(self) -> usize {
        Self::ALL.iter().position(|&s| s == self).unwrap_or(0)
    }

    fn cycled(self, dir: f32) -> Self {
        Self::ALL[stepped_index(self.index(), dir, Self::ALL.len())]
    }

    fn from_index(index: f32) -> Self {
        Self::ALL[clamped_index(index, Self::ALL.len())]
    }
}

/// Step a discrete field's index without wrapping: h/l stop at the ends, the
/// baseline behaviour for every slider-like field.
pub(crate) fn stepped_index(index: usize, dir: f32, len: usize) -> usize {
    let next = index as i64 + i64::from(dir.signum() as i32);
    next.clamp(0, len.saturating_sub(1) as i64) as usize
}

/// Numeric entry for a discrete field: round and clamp to the valid range.
pub(crate) fn clamped_index(index: f32, len: usize) -> usize {
    (index.round() as i64).clamp(0, len.saturating_sub(1) as i64) as usize
}

/// Deterministic per-index value in -1..1, keyed by the route seed. Pure hash,
/// no RNG state, so the UI and engine agree and offline renders stay identical.
fn seeded_unit(seed: u32, index: i64) -> f32 {
    let mut z = (index as u64)
        .wrapping_mul(0x9E37_79B9_7F4A_7C15)
        .wrapping_add(u64::from(seed))
        .wrapping_add(0x9E37_79B9_7F4A_7C15);
    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
    z ^= z >> 31;
    let unit = (z >> 40) as f32 / f32::from(1u16 << 8) / f32::from(1u16 << 8) / 256.0;
    unit * 2.0 - 1.0
}

fn smoothstep(t: f32) -> f32 {
    let t = t.clamp(0.0, 1.0);
    t * t * (3.0 - 2.0 * t)
}

/// Blends a ramp's raw value toward `next_cycle_start` over the last
/// `RAMP_WRAP_EASE` fraction of the cycle, so the value at phase 1 (== the
/// next cycle's phase 0) is reached smoothly instead of jumping there.
fn ease_ramp_wrap(phase: f32, raw: f32, next_cycle_start: f32) -> f32 {
    let window_start = 1.0 - RAMP_WRAP_EASE;
    if phase < window_start {
        return raw;
    }
    let t = smoothstep((phase - window_start) / RAMP_WRAP_EASE);
    raw + (next_cycle_start - raw) * t
}

/// Periodic shape value in -1..1 for a phase in 0..1. Random shapes return 0
/// here; they are evaluated from absolute beat position in `wave_at`.
fn periodic_shape_value(shape: LfoShape, phase: f32) -> f32 {
    match shape {
        LfoShape::Sine => (TAU * phase).sin(),
        LfoShape::Triangle => {
            if phase < 0.25 {
                4.0 * phase
            } else if phase < 0.75 {
                1.0 - 4.0 * (phase - 0.25)
            } else {
                -1.0 + 4.0 * (phase - 0.75)
            }
        }
        LfoShape::RampUp => ease_ramp_wrap(phase, 2.0 * phase - 1.0, -1.0),
        LfoShape::RampDown => ease_ramp_wrap(phase, 1.0 - 2.0 * phase, 1.0),
        LfoShape::Square => (SQUARE_SMOOTH * (TAU * phase).sin()).tanh(),
        // Random and Steps shapes are route-dependent: evaluated from seed or
        // the custom step array in `wave_at`/`step_value_at`, not from phase alone.
        LfoShape::RandomDrift | LfoShape::SampleHold | LfoShape::Steps => 0.0,
    }
}

/// Deterministic FNV-1a hash so each control's random modulator starts from an
/// independent seed without persisting per-route state.
fn seed_for_id(id: &str) -> u32 {
    let mut hash = 0x811C_9DC5u32;
    for byte in id.bytes() {
        hash ^= u32::from(byte);
        hash = hash.wrapping_mul(0x0100_0193);
    }
    hash
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum LfoField {
    Amount,
    Interval,
    Offset,
    Shape,
}

impl LfoField {
    pub(crate) const ALL: [LfoField; 4] = [Self::Amount, Self::Interval, Self::Offset, Self::Shape];

    pub(crate) fn label(self) -> &'static str {
        match self {
            Self::Shape => "shape",
            _ => self.spec().label,
        }
    }

    /// Only continuous slider fields carry a numeric spec; Shape is discrete.
    fn spec(self) -> &'static LfoFieldSpec {
        LFO_FIELD_SPECS
            .iter()
            .find(|spec| spec.field == self)
            .expect("every continuous LFO field has a spec")
    }

    /// Stable key qualifier for a field a macro can stack onto (see
    /// `AutomationState::field_macros`); None for Shape, which is discrete.
    /// Only meaningful on regular controls — a macro slider's own LFO never
    /// takes a stacked macro (no macro chasing itself).
    pub(crate) fn macro_key(self) -> Option<&'static str> {
        match self {
            Self::Amount => Some("lfo.amount"),
            Self::Interval => Some("lfo.interval"),
            Self::Offset => Some("lfo.offset"),
            Self::Shape => None,
        }
    }
}

/// One editable target inside a `Steps` shape's inline submenu: the sequence
/// length, the shared edge-glide, or one bipolar step value.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum StepTarget {
    Count,
    Glide,
    Value(usize),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum LfoEntry {
    Percent,
    Snap,
    Exact,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct LfoFieldSpec {
    pub(crate) field: LfoField,
    pub(crate) label: &'static str,
    pub(crate) min: f32,
    pub(crate) max: f32,
    pub(crate) step: f32,
    pub(crate) entry: LfoEntry,
    pub(crate) reset: f32,
    /// Interval-like fields lock to the musical beat grid (0.125 floor,
    /// sixteenths above) instead of a fixed linear step.
    pub(crate) beat_grid: bool,
}

impl LfoFieldSpec {
    pub(crate) fn adjust(self, value: f32, dir: f32) -> f32 {
        if self.field == LfoField::Interval {
            lfo_rate_adjust(value, dir)
        } else if self.beat_grid {
            beat_grid_adjust(value, dir, self.min, self.max)
        } else {
            self.quantize(value + dir * self.step)
        }
    }

    pub(crate) fn parse_value(self, value: f32) -> f32 {
        match self.entry {
            LfoEntry::Percent => normalize_unit_input(value).clamp(self.min, self.max),
            LfoEntry::Snap => self.quantize(value),
            LfoEntry::Exact => value.clamp(self.min, self.max),
        }
    }

    pub(crate) fn quantize(self, value: f32) -> f32 {
        if self.beat_grid {
            beat_grid_snap(value, self.min, self.max)
        } else {
            snap_step(value.clamp(self.min, self.max), self.step).clamp(self.min, self.max)
        }
    }

    pub(crate) fn ratio(self, value: f32) -> f32 {
        if self.field == LfoField::Interval {
            return ordered_step_ratio(value, LFO_RATE_ARROW_STEPS);
        }
        if self.beat_grid {
            return beat_grid_ratio(value, self.min, self.max);
        }
        let range = self.max - self.min;
        if range.abs() <= f32::EPSILON {
            0.0
        } else {
            ((value - self.min) / range).clamp(0.0, 1.0)
        }
    }
}

pub(crate) const LFO_FIELD_SPECS: &[LfoFieldSpec] = &[
    LfoFieldSpec {
        field: LfoField::Amount,
        label: "amount",
        min: 0.0,
        max: 1.0,
        step: AMOUNT_STEP,
        entry: LfoEntry::Percent,
        reset: 0.0,
        beat_grid: false,
    },
    LfoFieldSpec {
        field: LfoField::Interval,
        label: "rate",
        min: MIN_LFO_CYCLE_BEATS,
        max: MAX_LFO_CYCLE_BEATS,
        step: INTERVAL_STEP,
        entry: LfoEntry::Exact,
        reset: MIN_LFO_CYCLE_BEATS,
        beat_grid: true,
    },
    LfoFieldSpec {
        field: LfoField::Offset,
        label: "offset",
        min: 0.0,
        max: MAX_LFO_OFFSET_BEATS,
        step: OFFSET_STEP,
        entry: LfoEntry::Snap,
        reset: 0.0,
        beat_grid: true,
    },
];

pub(crate) const LFO_RATE_ARROW_STEPS: &[f32] = &[
    0.125, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75, 4.0,
    8.0, 12.0, 16.0, 32.0, 64.0,
];

fn lfo_rate_adjust(value: f32, dir: f32) -> f32 {
    if dir > 0.0 {
        LFO_RATE_ARROW_STEPS
            .iter()
            .copied()
            .find(|step| *step > value + f32::EPSILON)
            .unwrap_or(MAX_LFO_CYCLE_BEATS)
    } else {
        LFO_RATE_ARROW_STEPS
            .iter()
            .rev()
            .copied()
            .find(|step| *step < value - f32::EPSILON)
            .unwrap_or(MIN_LFO_CYCLE_BEATS)
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct LfoPickup {
    pub(crate) from_cycle_beats: f32,
    pub(crate) at_beat: f64,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct LfoRoute {
    pub(crate) depth_ratio: f32,
    pub(crate) cycle_beats: f32,
    pub(crate) phase_offset_beats: f32,
    pub(crate) shape: LfoShape,
    /// Seed for random shapes; hashed with the cycle index to produce values.
    pub(crate) seed: u32,
    /// Custom staircase for `LfoShape::Steps`; only the first `step_count`
    /// entries are live. Bipolar (-1..1), inert unless the shape is `Steps`.
    /// Each step spans one LFO interval (`cycle_beats`), so the full pattern
    /// lasts `step_count` intervals — raising the count extends the pattern.
    pub(crate) steps: [f32; MAX_LFO_STEPS],
    pub(crate) step_count: u8,
    /// Edge-glide fraction (0..1): how much of each step window eases in from
    /// the previous step's value instead of holding flat. See `step_value_at`.
    pub(crate) step_glide: f32,
    /// Transient handoff after a live rate edit. The old globally anchored
    /// clock keeps playing until it next crosses the new clock, then the new
    /// rate takes over without rewriting the user's offset.
    pub(crate) pickup: Option<LfoPickup>,
}

impl Default for LfoRoute {
    fn default() -> Self {
        Self {
            depth_ratio: DEFAULT_LFO_DEPTH_RATIO,
            cycle_beats: DEFAULT_LFO_CYCLE_BEATS,
            phase_offset_beats: 0.0,
            shape: LfoShape::Sine,
            seed: 0,
            steps: DEFAULT_LFO_STEPS,
            step_count: DEFAULT_LFO_STEP_COUNT,
            step_glide: DEFAULT_LFO_STEP_GLIDE,
            pickup: None,
        }
    }
}

impl LfoRoute {
    pub(crate) fn with_seed(seed: u32) -> Self {
        Self {
            seed,
            ..Self::default()
        }
    }

    pub(crate) fn phase_at(&self, beat: f64) -> f64 {
        self.phase_at_cycle(beat, self.active_cycle_at(beat))
    }

    fn phase_at_cycle(&self, beat: f64, cycle_beats: f32) -> f64 {
        global_lfo_position(beat, cycle_beats, self.phase_offset_beats).1
    }

    fn active_cycle_at(&self, beat: f64) -> f32 {
        self.pickup
            .filter(|pickup| beat < pickup.at_beat)
            .map_or(self.cycle_beats, |pickup| pickup.from_cycle_beats)
    }

    /// Absolute cycle index and phase-in-cycle for the given beat. Random shapes
    /// hash the cycle index; the fractional part doubles as the periodic phase.
    fn cycle_index_and_phase_for(&self, beat: f64, cycle_beats: f32) -> (i64, f32) {
        let (index, phase) = global_lfo_position(beat, cycle_beats, self.phase_offset_beats);
        (index, phase as f32)
    }

    /// Oscillator output in -1..1 at the given beat; depth scaling is the
    /// caller's job. Single source of truth for both the engine and the lane.
    pub(crate) fn wave_at(&self, beat: f64) -> f32 {
        self.wave_at_cycle(beat, self.active_cycle_at(beat))
    }

    fn wave_at_cycle(&self, beat: f64, cycle_beats: f32) -> f32 {
        let (index, phase) = self.cycle_index_and_phase_for(beat, cycle_beats);
        match self.shape {
            LfoShape::SampleHold => seeded_unit(self.seed, index),
            LfoShape::RandomDrift => {
                let a = seeded_unit(self.seed, index);
                let b = seeded_unit(self.seed, index + 1);
                a + (b - a) * smoothstep(phase)
            }
            LfoShape::Steps => {
                let count = self.active_step_count();
                self.step_value_at(index.rem_euclid(count as i64) as usize, phase)
            }
            shape => periodic_shape_value(shape, phase),
        }
    }

    /// Live step count, clamped into the valid `1..=MAX_LFO_STEPS` range.
    pub(crate) fn active_step_count(&self) -> usize {
        (self.step_count as usize).clamp(1, MAX_LFO_STEPS)
    }

    /// Staircase value in -1..1 for step `idx` at fraction `frac` (0..1)
    /// through that step. Each step spans one LFO interval and holds its
    /// value, easing in from the previous step's value over the first
    /// `step_glide` fraction of the step. Because step 0 eases from the last
    /// step, the curve is value-continuous across the pattern wrap too (at
    /// `step_glide` 0 it hard-steps and clicks, same as sample & hold).
    fn step_value_at(&self, idx: usize, frac: f32) -> f32 {
        let count = self.active_step_count();
        let idx = idx.min(count - 1);
        let cur = self.steps[idx];
        let glide = self.step_glide.clamp(0.0, 1.0);
        if glide <= f32::EPSILON || frac >= glide {
            return cur;
        }
        let prev = self.steps[(idx + count - 1) % count];
        prev + (cur - prev) * smoothstep(frac / glide)
    }

    /// Periodic shape value in -1..1 at a phase in 0..1, for lane drawing.
    /// For `Steps` the phase spans the whole pattern (`step_count` intervals),
    /// matching `pattern_phase_at`. Random shapes return 0 here; draw them
    /// from `wave_at` over time instead.
    pub(crate) fn shape_value_at_phase(&self, phase: f32) -> f32 {
        match self.shape {
            LfoShape::Steps => {
                let count = self.active_step_count();
                let scaled = phase.rem_euclid(1.0) * count as f32;
                let idx = (scaled.floor() as usize).min(count - 1);
                self.step_value_at(idx, scaled - idx as f32)
            }
            _ => periodic_shape_value(self.shape, phase),
        }
    }

    /// Phase of the full drawn pattern at `beat`: one interval for periodic
    /// shapes, `step_count` intervals for `Steps` (each step spans one
    /// interval). Drives the lane's bright head so it tracks what plays.
    pub(crate) fn pattern_phase_at(&self, beat: f64) -> f64 {
        match self.shape {
            LfoShape::Steps => {
                let cycle = f64::from(self.active_cycle_at(beat).max(MIN_LFO_CYCLE_BEATS));
                let t = (beat + f64::from(self.phase_offset_beats)) / cycle;
                (t / self.active_step_count() as f64).rem_euclid(1.0)
            }
            _ => self.phase_at(beat),
        }
    }

    /// Adjust a step submenu target by one h/l press.
    pub(crate) fn adjust_step(&mut self, target: StepTarget, dir: f32) {
        self.pickup = None;
        match target {
            StepTarget::Count => {
                self.set_step_count(self.step_count as i32 + dir.signum() as i32);
            }
            StepTarget::Glide => {
                self.step_glide = (self.step_glide + dir * STEP_GLIDE_STEP).clamp(0.0, 1.0);
            }
            StepTarget::Value(i) => {
                if let Some(value) = self.steps.get_mut(i) {
                    *value = (*value + dir * STEP_VALUE_STEP).clamp(-1.0, 1.0);
                }
            }
        }
    }

    /// Numeric entry for a step target: count is a whole number, glide a
    /// unipolar percent, a step value a bipolar percent (`-100`..`100`).
    pub(crate) fn set_step(&mut self, target: StepTarget, value: f32) {
        self.pickup = None;
        match target {
            StepTarget::Count => self.set_step_count(value.round() as i32),
            StepTarget::Glide => self.step_glide = (value / 100.0).clamp(0.0, 1.0),
            StepTarget::Value(i) => {
                if let Some(step) = self.steps.get_mut(i) {
                    *step = (value / 100.0).clamp(-1.0, 1.0);
                }
            }
        }
    }

    pub(crate) fn reset_step(&mut self, target: StepTarget) {
        self.pickup = None;
        match target {
            StepTarget::Count => self.step_count = DEFAULT_LFO_STEP_COUNT,
            StepTarget::Glide => self.step_glide = DEFAULT_LFO_STEP_GLIDE,
            StepTarget::Value(i) => {
                if let Some(step) = self.steps.get_mut(i) {
                    *step = 0.0;
                }
            }
        }
    }

    fn set_step_count(&mut self, count: i32) {
        self.step_count = count.clamp(1, MAX_LFO_STEPS as i32) as u8;
    }

    pub(crate) fn step_ratio(&self, target: StepTarget) -> f32 {
        match target {
            StepTarget::Count => {
                (self.active_step_count() - 1) as f32 / (MAX_LFO_STEPS - 1).max(1) as f32
            }
            StepTarget::Glide => self.step_glide.clamp(0.0, 1.0),
            StepTarget::Value(i) => (self.steps.get(i).copied().unwrap_or(0.0) + 1.0) / 2.0,
        }
    }

    pub(crate) fn step_display(&self, target: StepTarget) -> String {
        match target {
            StepTarget::Count => format!("{}", self.active_step_count()),
            StepTarget::Glide => format!("{:.0}%", self.step_glide * 100.0),
            StepTarget::Value(i) => {
                format!("{:+.0}%", self.steps.get(i).copied().unwrap_or(0.0) * 100.0)
            }
        }
    }

    pub(crate) fn step_label(&self, target: StepTarget) -> String {
        match target {
            StepTarget::Count => "steps".to_string(),
            StepTarget::Glide => "glide".to_string(),
            StepTarget::Value(i) => format!("· step {}", i + 1),
        }
    }

    /// Re-roll the random seed to a new but repeatable pattern.
    pub(crate) fn reseed(&mut self) {
        self.seed = self
            .seed
            .wrapping_mul(1_664_525)
            .wrapping_add(1_013_904_223)
            ^ 0x5DEE_CE66;
    }

    pub(crate) fn adjust_field_at(&mut self, field: LfoField, dir: f32, beat: f64) {
        match field {
            LfoField::Shape => {
                self.shape = self.shape.cycled(dir);
                self.pickup = None;
            }
            LfoField::Amount => {
                self.depth_ratio = field.spec().adjust(self.depth_ratio, dir);
            }
            LfoField::Interval => {
                self.set_cycle_with_pickup(field.spec().adjust(self.cycle_beats, dir), beat);
            }
            LfoField::Offset => {
                self.phase_offset_beats = field.spec().adjust(self.phase_offset_beats, dir);
                self.pickup = None;
            }
        }
    }

    pub(crate) fn set_field_at(&mut self, field: LfoField, value: f32, beat: f64) {
        match field {
            LfoField::Shape => {
                self.shape = LfoShape::from_index(value);
                self.pickup = None;
            }
            LfoField::Amount => self.depth_ratio = field.spec().parse_value(value),
            LfoField::Interval => {
                self.set_cycle_with_pickup(field.spec().parse_value(value), beat);
            }
            LfoField::Offset => {
                self.phase_offset_beats = field.spec().parse_value(value);
                self.pickup = None;
            }
        }
    }

    /// Set a time field to an exact value, clamped to range but not snapped
    /// to the beat grid — used while the field is being driven in ms.
    pub(crate) fn set_field_raw_at(&mut self, field: LfoField, value: f32, beat: f64) {
        match field {
            LfoField::Interval => self
                .set_cycle_with_pickup(value.clamp(MIN_LFO_CYCLE_BEATS, MAX_LFO_CYCLE_BEATS), beat),
            LfoField::Offset => {
                self.phase_offset_beats = value.clamp(0.0, MAX_LFO_OFFSET_BEATS);
                self.pickup = None;
            }
            _ => self.set_field_at(field, value, beat),
        }
    }

    pub(crate) fn reset_field_at(&mut self, field: LfoField, beat: f64) {
        match field {
            LfoField::Shape => {
                self.shape = LfoShape::Sine;
                self.pickup = None;
            }
            LfoField::Amount => self.depth_ratio = field.spec().reset,
            LfoField::Interval => self.set_cycle_with_pickup(field.spec().reset, beat),
            LfoField::Offset => {
                self.phase_offset_beats = field.spec().reset;
                self.pickup = None;
            }
        }
    }

    pub(crate) fn field_ratio(&self, field: LfoField) -> f32 {
        match field {
            LfoField::Shape => self.shape.index() as f32 / (LfoShape::ALL.len() - 1).max(1) as f32,
            LfoField::Amount => field.spec().ratio(self.depth_ratio),
            LfoField::Interval => field.spec().ratio(self.cycle_beats),
            LfoField::Offset => field.spec().ratio(self.phase_offset_beats),
        }
    }

    pub(crate) fn field_display(&self, field: LfoField) -> String {
        match field {
            LfoField::Shape => self.shape.label().to_string(),
            LfoField::Amount => format!("{:.0}%", self.depth_ratio * 100.0),
            LfoField::Interval => format!("{:.2} beats", self.cycle_beats),
            LfoField::Offset => format!("{:.2} beats", self.phase_offset_beats),
        }
    }

    fn set_cycle_with_pickup(&mut self, cycle_beats: f32, beat: f64) {
        let old_cycle = self.active_cycle_at(beat);
        if (old_cycle - cycle_beats).abs() <= f32::EPSILON {
            self.cycle_beats = cycle_beats;
            self.pickup = None;
            return;
        }
        self.cycle_beats = cycle_beats;
        self.pickup = next_wave_crossing(self, old_cycle, cycle_beats, beat).and_then(|at_beat| {
            (at_beat > beat + f64::EPSILON).then_some(LfoPickup {
                from_cycle_beats: old_cycle,
                at_beat,
            })
        });
    }

    /// Morph an optional route on each side of a leg transition: `depth_ratio`
    /// glides by `tt` (0..1, matching `ControlKind::Gain`'s treatment of
    /// every other slider), every other field snaps together to `to`'s value
    /// once `use_to` flips true, matching `ControlKind::Discrete`'s
    /// structural-snap treatment. A route missing on one side glides its
    /// depth to/from 0 while holding the present side's other fields — it
    /// fades in or out rather than popping, and naturally disappears once the
    /// leg's `to` state becomes the next leg's `from`. See `morph_scalar_route`
    /// for the shared 4-arm glide/snap logic.
    fn morph(
        from: Option<&LfoRoute>,
        to: Option<&LfoRoute>,
        tt: f32,
        use_to: bool,
    ) -> Option<LfoRoute> {
        morph_scalar_route(
            from,
            to,
            tt,
            use_to,
            |r| r.depth_ratio,
            |r, v| r.depth_ratio = v,
        )
    }
}

/// Every LFO derives position from the shared transport beat. A zero offset
/// therefore puts every route with the same rate on the same song-wide grid,
/// regardless of which control owns it or when its editor was opened.
fn global_lfo_position(beat: f64, cycle_beats: f32, offset_beats: f32) -> (i64, f64) {
    let cycle = f64::from(cycle_beats.max(MIN_LFO_CYCLE_BEATS));
    let position = (beat + f64::from(offset_beats)) / cycle;
    let index = position.floor();
    (index as i64, position - index)
}

/// Shared glide/snap morph for a route type whose only "level" field crosses
/// a leg transition on a glide while every other field snaps: on both sides
/// present, all-but-`get`/`set` fields snap to `to` once `use_to` flips true
/// while the level field glides `tt` between the two; on only one side
/// present, the level field glides to/from 0 while the present side's other
/// fields hold, so the route fades in or out instead of popping.
fn morph_scalar_route<T: Copy>(
    from: Option<&T>,
    to: Option<&T>,
    tt: f32,
    use_to: bool,
    get: fn(&T) -> f32,
    set: fn(&mut T, f32),
) -> Option<T> {
    match (from, to) {
        (Some(f), Some(t)) => {
            let mut route = if use_to { *t } else { *f };
            set(&mut route, get(f) + (get(t) - get(f)) * tt);
            Some(route)
        }
        (Some(f), None) => {
            let mut route = *f;
            set(&mut route, get(f) * (1.0 - tt));
            Some(route)
        }
        (None, Some(t)) => {
            let mut route = *t;
            set(&mut route, get(t) * tt);
            Some(route)
        }
        (None, None) => None,
    }
}

fn next_wave_crossing(
    route: &LfoRoute,
    old_cycle_beats: f32,
    new_cycle_beats: f32,
    beat: f64,
) -> Option<f64> {
    let delta_at =
        |at| route.wave_at_cycle(at, old_cycle_beats) - route.wave_at_cycle(at, new_cycle_beats);
    let mut previous_beat = beat;
    let mut previous_delta = delta_at(beat);
    if previous_delta.abs() <= PICKUP_CROSSING_EPSILON {
        return Some(beat);
    }

    let horizon = f64::from(old_cycle_beats.max(new_cycle_beats)) * 2.0;
    let steps = (horizon / PICKUP_SCAN_STEP_BEATS).ceil() as usize;
    let mut closest = (previous_delta.abs(), beat);
    for step in 1..=steps {
        let next_beat = beat + step as f64 * PICKUP_SCAN_STEP_BEATS;
        let next_delta = delta_at(next_beat);
        if next_delta.abs() < closest.0 {
            closest = (next_delta.abs(), next_beat);
        }
        if next_delta.abs() <= PICKUP_CROSSING_EPSILON {
            return Some(next_beat);
        }
        if previous_delta.signum() != next_delta.signum() {
            let mut lo = previous_beat;
            let mut hi = next_beat;
            let lo_sign = previous_delta.signum();
            for _ in 0..20 {
                let mid = (lo + hi) * 0.5;
                if delta_at(mid).signum() == lo_sign {
                    lo = mid;
                } else {
                    hi = mid;
                }
            }
            return Some((lo + hi) * 0.5);
        }
        previous_beat = next_beat;
        previous_delta = next_delta;
    }

    // Discrete/random shapes may not have a literal continuous crossing.
    // Hand off at their closest encounter within two cycles instead.
    Some(closest.1)
}

// ============================================================
// Envelope routes
// ============================================================

/// What re-triggers a one-shot envelope. `EveryBeats` cycles on a musical grid,
/// `OnKick` fires with the kick, and `Once` is the set-and-forget macro that
/// sweeps a single time from song start.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum EnvTrigger {
    EveryBeats(f32),
    OnKick,
    Once,
}

impl EnvTrigger {
    /// Ordered presets the Trigger field cycles through, folding the every-N
    /// interval choices and the macro one-shot into one discrete field.
    const CYCLE: [EnvTrigger; 8] = [
        Self::EveryBeats(1.0),
        Self::EveryBeats(2.0),
        Self::EveryBeats(4.0),
        Self::EveryBeats(8.0),
        Self::EveryBeats(16.0),
        Self::EveryBeats(32.0),
        Self::OnKick,
        Self::Once,
    ];

    fn index(self) -> usize {
        Self::CYCLE.iter().position(|&t| t == self).unwrap_or(2) // default: every 4 beats
    }

    fn cycled(self, dir: f32) -> Self {
        Self::CYCLE[stepped_index(self.index(), dir, Self::CYCLE.len())]
    }

    fn from_index(index: f32) -> Self {
        Self::CYCLE[clamped_index(index, Self::CYCLE.len())]
    }

    fn label(self) -> String {
        match self {
            Self::EveryBeats(n) => format!("every {n:.0} beats"),
            Self::OnKick => "on kick".to_string(),
            Self::Once => "once (macro)".to_string(),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum EnvField {
    Amount,
    Attack,
    Decay,
    Trigger,
}

impl EnvField {
    pub(crate) const ALL: [EnvField; 4] = [Self::Amount, Self::Attack, Self::Decay, Self::Trigger];

    pub(crate) fn label(self) -> &'static str {
        match self {
            Self::Amount => "amount",
            Self::Attack => "attack",
            Self::Decay => "decay",
            Self::Trigger => "trigger",
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct EnvelopeRoute {
    /// Bipolar sweep depth in -1..1; positive blooms up, negative dips down.
    pub(crate) amount: f32,
    pub(crate) attack_beats: f32,
    /// Fall time back to base; 0 holds at the peak indefinitely (macro hold).
    pub(crate) decay_beats: f32,
    pub(crate) trigger: EnvTrigger,
}

impl Default for EnvelopeRoute {
    fn default() -> Self {
        Self {
            amount: 0.0,
            attack_beats: DEFAULT_ENV_ATTACK_BEATS,
            decay_beats: DEFAULT_ENV_DECAY_BEATS,
            trigger: EnvTrigger::EveryBeats(4.0),
        }
    }
}

impl EnvelopeRoute {
    /// Beats elapsed since the most recent trigger, or None before the first
    /// trigger has fired. Pure function of the context so UI and engine agree.
    fn beats_since_trigger(&self, ctx: ModContext) -> Option<f32> {
        match self.trigger {
            EnvTrigger::EveryBeats(n) => {
                let n = f64::from(n.max(ENV_BEATS_STEP));
                if ctx.beat < 0.0 {
                    return None;
                }
                Some(ctx.beat.rem_euclid(n) as f32)
            }
            EnvTrigger::Once => {
                if ctx.beat < 0.0 {
                    None
                } else {
                    Some(ctx.beat as f32)
                }
            }
            EnvTrigger::OnKick => {
                let interval = f64::from(ctx.kick_interval_beats.max(1.0 / 64.0));
                let offset = f64::from(ctx.kick_offset_beats).rem_euclid(interval);
                let slot = ((ctx.beat - offset) / interval).floor();
                let last = offset + slot * interval;
                if last < -1e-9 {
                    None
                } else {
                    Some((ctx.beat - last) as f32)
                }
            }
        }
    }

    /// One-shot AD level in 0..1 at the given beat. Zero attack fires instantly;
    /// zero decay holds at the peak (set-and-forget macro).
    pub(crate) fn level_at(&self, ctx: ModContext) -> f32 {
        let Some(since) = self.beats_since_trigger(ctx) else {
            return 0.0;
        };
        self.level_for_elapsed(since)
    }

    fn level_for_elapsed(&self, since: f32) -> f32 {
        if since < 0.0 {
            0.0
        } else if self.attack_beats > 0.0 && since < self.attack_beats {
            since / self.attack_beats
        } else if self.decay_beats <= 0.0 {
            1.0
        } else if since < self.attack_beats + self.decay_beats {
            1.0 - (since - self.attack_beats) / self.decay_beats
        } else {
            0.0
        }
    }

    /// Beats spanned by one trigger period, used to scope the animated lane.
    pub(crate) fn window_beats(&self) -> f32 {
        match self.trigger {
            EnvTrigger::EveryBeats(n) => n.max(ENV_BEATS_STEP),
            EnvTrigger::OnKick => self.attack_beats + self.decay_beats.max(ENV_BEATS_STEP),
            EnvTrigger::Once => (self.attack_beats + self.decay_beats).max(ENV_BEATS_STEP),
        }
    }

    /// Envelope level at a given elapsed beat, for drawing the lane curve.
    pub(crate) fn level_for_lane(&self, since: f32) -> f32 {
        self.level_for_elapsed(since)
    }

    /// Where the live phase head sits along the lane window, 0..1.
    pub(crate) fn lane_head_phase(&self, ctx: ModContext) -> f32 {
        match self.beats_since_trigger(ctx) {
            Some(since) => (since / self.window_beats().max(ENV_BEATS_STEP)).clamp(0.0, 1.0),
            None => 0.0,
        }
    }

    pub(crate) fn adjust_field(&mut self, field: EnvField, dir: f32) {
        match field {
            EnvField::Amount => {
                self.amount = (self.amount + dir * ENV_AMOUNT_STEP).clamp(-1.0, 1.0);
            }
            EnvField::Attack => {
                self.attack_beats =
                    snap_step(self.attack_beats + dir * ENV_BEATS_STEP, ENV_BEATS_STEP)
                        .clamp(0.0, MAX_ENV_ATTACK_BEATS);
            }
            EnvField::Decay => {
                self.decay_beats =
                    snap_step(self.decay_beats + dir * ENV_BEATS_STEP, ENV_BEATS_STEP)
                        .clamp(0.0, MAX_ENV_DECAY_BEATS);
            }
            EnvField::Trigger => self.trigger = self.trigger.cycled(dir),
        }
    }

    pub(crate) fn set_field(&mut self, field: EnvField, value: f32) {
        match field {
            EnvField::Amount => {
                self.amount = (value / 100.0).clamp(-1.0, 1.0);
            }
            EnvField::Attack => {
                self.attack_beats =
                    snap_step(value, ENV_BEATS_STEP).clamp(0.0, MAX_ENV_ATTACK_BEATS);
            }
            EnvField::Decay => {
                self.decay_beats = snap_step(value, ENV_BEATS_STEP).clamp(0.0, MAX_ENV_DECAY_BEATS);
            }
            EnvField::Trigger => self.trigger = EnvTrigger::from_index(value),
        }
    }

    /// Set a time field to an exact value, clamped to range but not snapped
    /// to the beat grid — used while the field is being driven in ms.
    pub(crate) fn set_field_raw(&mut self, field: EnvField, value: f32) {
        match field {
            EnvField::Attack => self.attack_beats = value.clamp(0.0, MAX_ENV_ATTACK_BEATS),
            EnvField::Decay => self.decay_beats = value.clamp(0.0, MAX_ENV_DECAY_BEATS),
            EnvField::Amount | EnvField::Trigger => self.set_field(field, value),
        }
    }

    pub(crate) fn reset_field(&mut self, field: EnvField) {
        let defaults = EnvelopeRoute::default();
        match field {
            EnvField::Amount => self.amount = defaults.amount,
            EnvField::Attack => self.attack_beats = defaults.attack_beats,
            EnvField::Decay => self.decay_beats = defaults.decay_beats,
            EnvField::Trigger => self.trigger = defaults.trigger,
        }
    }

    pub(crate) fn field_ratio(&self, field: EnvField) -> f32 {
        match field {
            EnvField::Amount => (self.amount * 0.5 + 0.5).clamp(0.0, 1.0),
            EnvField::Attack => (self.attack_beats / MAX_ENV_ATTACK_BEATS).clamp(0.0, 1.0),
            EnvField::Decay => (self.decay_beats / MAX_ENV_DECAY_BEATS).clamp(0.0, 1.0),
            EnvField::Trigger => {
                self.trigger.index() as f32 / (EnvTrigger::CYCLE.len() - 1).max(1) as f32
            }
        }
    }

    pub(crate) fn field_display(&self, field: EnvField) -> String {
        match field {
            EnvField::Amount => format!("{:+.0}%", self.amount * 100.0),
            EnvField::Attack => format!("{:.2} beats", self.attack_beats),
            EnvField::Decay => {
                if self.decay_beats <= 0.0 {
                    "hold".to_string()
                } else {
                    format!("{:.2} beats", self.decay_beats)
                }
            }
            EnvField::Trigger => self.trigger.label(),
        }
    }

    /// Morph an optional envelope route across a leg transition; same
    /// glide/snap split as `LfoRoute::morph` with `amount` as the level
    /// field. See `morph_scalar_route` for the full rationale.
    fn morph(
        from: Option<&EnvelopeRoute>,
        to: Option<&EnvelopeRoute>,
        tt: f32,
        use_to: bool,
    ) -> Option<EnvelopeRoute> {
        morph_scalar_route(from, to, tt, use_to, |r| r.amount, |r, v| r.amount = v)
    }
}

// ============================================================
// Macro routes
// ============================================================

const MACRO_AMOUNT_STEP: f32 = 0.01;

/// One of the four macro sliders' independent amount fields on a route.
/// There is no "target" selection any more: every macro assignment (a
/// regular control's `v` route, or a field macro stacked on an LFO field)
/// holds a bipolar amount for all four macro sliders at once, so a single
/// control can ride several macros simultaneously.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct MacroField(usize);

impl MacroField {
    pub(crate) const ALL: [MacroField; MACRO_COUNT] = {
        let mut all = [MacroField(0); MACRO_COUNT];
        let mut i = 0;
        while i < MACRO_COUNT {
            all[i] = MacroField(i);
            i += 1;
        }
        all
    };

    pub(crate) fn label(self) -> String {
        format!("macro {}", self.0 + 1)
    }

    fn index(self) -> usize {
        self.0
    }
}

/// Assignment of a control (or a single stacked LFO field) to the macro
/// sliders. Each of the four macro sliders has its own independent bipolar
/// amount in -1..1, applied to the control's full range and summed — a
/// control can ride several macros at once, each set directly, none of them
/// requiring the others to be neutral.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct MacroRoute {
    pub(crate) amounts: [f32; MACRO_COUNT],
}

impl Default for MacroRoute {
    fn default() -> Self {
        Self {
            amounts: [0.0; MACRO_COUNT],
        }
    }
}

impl MacroRoute {
    pub(crate) fn is_neutral(self) -> bool {
        self.amounts.iter().all(|a| a.abs() <= f32::EPSILON)
    }

    pub(crate) fn adjust_field(&mut self, field: MacroField, dir: f32) {
        let a = &mut self.amounts[field.index()];
        *a = (*a + dir * MACRO_AMOUNT_STEP).clamp(-1.0, 1.0);
    }

    pub(crate) fn set_field(&mut self, field: MacroField, value: f32) {
        self.amounts[field.index()] = (value / 100.0).clamp(-1.0, 1.0);
    }

    pub(crate) fn reset_field(&mut self, field: MacroField) {
        self.amounts[field.index()] = 0.0;
    }

    pub(crate) fn field_ratio(self, field: MacroField) -> f32 {
        (self.amounts[field.index()] * 0.5 + 0.5).clamp(0.0, 1.0)
    }

    pub(crate) fn field_display(self, field: MacroField) -> String {
        format!("{:+.0}%", self.amounts[field.index()] * 100.0)
    }

    /// Compact summary of every non-neutral slot, e.g. "m1 +30%  m3 -50%",
    /// for the closed chip line. "none" when every slot is at zero.
    pub(crate) fn summary(self) -> String {
        let parts: Vec<String> = self
            .amounts
            .iter()
            .enumerate()
            .filter(|(_, a)| a.abs() > f32::EPSILON)
            .map(|(i, a)| format!("m{} {:+.0}%", i + 1, a * 100.0))
            .collect();
        if parts.is_empty() {
            "none".to_string()
        } else {
            parts.join("  ")
        }
    }

    /// Combined bipolar contribution ratio: sum over every macro slider of
    /// this route's amount times that slider's live value, each individually
    /// clamped before summing. Multiplied by the control's range by the
    /// caller. 0.0 when neutral, matching the "no effect" case.
    fn combined(self, macro_values: &[f32; MACRO_COUNT]) -> f32 {
        self.amounts
            .iter()
            .zip(macro_values)
            .map(|(a, v)| a.clamp(-1.0, 1.0) * v.clamp(0.0, 1.0))
            .sum()
    }

    /// Morph an optional macro route across a leg transition. Every slot is
    /// a plain bipolar amount, so there's no snap-field split — the whole
    /// route just glides by `tt`, fading in/out toward 0 on the side it's
    /// missing from.
    fn morph(from: Option<&MacroRoute>, to: Option<&MacroRoute>, tt: f32) -> Option<MacroRoute> {
        match (from, to) {
            (Some(f), Some(t)) => Some(MacroRoute {
                amounts: std::array::from_fn(|i| f.amounts[i] + (t.amounts[i] - f.amounts[i]) * tt),
            }),
            (Some(f), None) => Some(MacroRoute {
                amounts: f.amounts.map(|a| a * (1.0 - tt)),
            }),
            (None, Some(t)) => Some(MacroRoute {
                amounts: t.amounts.map(|a| a * tt),
            }),
            (None, None) => None,
        }
    }

    /// Best-case full reach: how far the combined contribution could swing
    /// the control below (negative) and above (positive) base if every macro
    /// slider it rides independently reached its own extreme (1.0). Used by
    /// the reach-shadow marker, not the live value.
    pub(crate) fn swing(self, range: f32) -> (f32, f32) {
        let mut lo = 0.0;
        let mut hi = 0.0;
        for a in self.amounts {
            let a = a.clamp(-1.0, 1.0);
            if a < 0.0 {
                lo += a * range;
            } else {
                hi += a * range;
            }
        }
        (lo, hi)
    }
}

// ============================================================
// Automation state
// ============================================================

#[derive(Clone, Copy, Debug, PartialEq)]
struct OpenEditor {
    address: ControlAddress,
    kind: ModKind,
}

#[derive(Clone, Default)]
pub(crate) struct AutomationState {
    routes: BTreeMap<ControlAddress, LfoRoute>,
    envelopes: BTreeMap<ControlAddress, EnvelopeRoute>,
    macros: BTreeMap<ControlAddress, MacroRoute>,
    /// A macro stacked onto a single numeric field of an open LFO editor
    /// (amount, interval, or offset), keyed the same way as `FlippedUnits`:
    /// `unit_key(control id, Some(field key))`. Only ever created when the
    /// user explicitly presses `v` on that field — never on by default —
    /// and pruned back out on close if left at neutral, same as every other
    /// route kind.
    field_macros: BTreeMap<String, MacroRoute>,
    open: Option<OpenEditor>,
    /// The field-macro key currently expanded for editing, if any. Only
    /// meaningful while `open` points at the same control's LFO editor.
    open_field: Option<String>,
}

impl AutomationState {
    pub(crate) fn open_or_create(&mut self, address: ControlAddress) -> &mut LfoRoute {
        let route = self
            .routes
            .entry(address)
            .or_insert_with(|| LfoRoute::with_seed(seed_for_id(address.id())));
        self.open = Some(OpenEditor {
            address,
            kind: ModKind::Lfo,
        });
        route
    }

    pub(crate) fn open_or_create_envelope(
        &mut self,
        address: ControlAddress,
    ) -> &mut EnvelopeRoute {
        let route = self.envelopes.entry(address).or_default();
        self.open = Some(OpenEditor {
            address,
            kind: ModKind::Envelope,
        });
        route
    }

    pub(crate) fn open_or_create_macro(&mut self, address: ControlAddress) -> &mut MacroRoute {
        let route = self.macros.entry(address).or_default();
        self.open = Some(OpenEditor {
            address,
            kind: ModKind::Macro,
        });
        route
    }

    /// Remove the route backing the open editor and close it. The x gesture:
    /// explicit, worked on the first try, unlike double-tap.
    pub(crate) fn remove_open_route(&mut self) {
        let Some(open) = self.open.take() else {
            return;
        };
        match open.kind {
            ModKind::Lfo => {
                self.routes.remove(&open.address);
                self.remove_field_macros_for(open.address, "lfo.");
            }
            ModKind::Envelope => {
                self.envelopes.remove(&open.address);
            }
            ModKind::Macro => {
                self.macros.remove(&open.address);
            }
        }
        self.open_field = None;
    }

    /// Strip every modulator from a control (LFO, envelope, macro route,
    /// field macros), closing the editor if it was open on that control.
    pub(crate) fn clear_control(&mut self, address: ControlAddress) {
        self.routes.remove(&address);
        self.envelopes.remove(&address);
        self.macros.remove(&address);
        self.remove_field_macros_for(address, "");
        if self.open.is_some_and(|open| open.address == address) {
            self.open = None;
        }
    }

    fn remove_field_macros_for(&mut self, address: ControlAddress, field_prefix: &str) {
        let prefix = format!("{}#{field_prefix}", address.id());
        self.field_macros.retain(|key, _| !key.starts_with(&prefix));
        if self
            .open_field
            .as_ref()
            .is_some_and(|key| key.starts_with(&prefix))
        {
            self.open_field = None;
        }
    }

    /// Close the editor; a route left at neutral amount is dead weight and is
    /// removed so it never colours the UI or the song code.
    pub(crate) fn close_editor(&mut self) {
        self.close_open_field();
        let Some(open) = self.open.take() else {
            return;
        };
        match open.kind {
            ModKind::Lfo => {
                // depth_ratio alone isn't the whole story: a field macro
                // stacked on lfo.amount (or interval/offset) can still be
                // driving the route externally even while its own base
                // amount sits at neutral, so the route stays live and must
                // not be pruned out from under it.
                let base_neutral = self
                    .routes
                    .get(&open.address)
                    .is_some_and(|route| route.depth_ratio <= f32::EPSILON);
                let field_macro_prefix = format!("{}#lfo.", open.address.id());
                let has_live_field_macro = self.field_macros.iter().any(|(key, route)| {
                    key.starts_with(&field_macro_prefix) && !route.is_neutral()
                });
                if base_neutral && !has_live_field_macro {
                    self.routes.remove(&open.address);
                }
            }
            ModKind::Envelope => {
                if self
                    .envelopes
                    .get(&open.address)
                    .is_some_and(|route| route.amount.abs() <= f32::EPSILON)
                {
                    self.envelopes.remove(&open.address);
                }
            }
            ModKind::Macro => {
                if self
                    .macros
                    .get(&open.address)
                    .is_some_and(|route| route.is_neutral())
                {
                    self.macros.remove(&open.address);
                }
            }
        }
    }

    /// The field-macro key currently expanded for editing, if any.
    pub(crate) fn open_field(&self) -> Option<&str> {
        self.open_field.as_deref()
    }

    /// Toggle the nested macro editor for a field: same key closes (pruning
    /// it if left neutral), any other key swaps to it (creating it
    /// audible-neutral). This is the only way a field macro is created —
    /// never on by default.
    pub(crate) fn toggle_open_field(&mut self, key: String) {
        if self.open_field.as_deref() == Some(key.as_str()) {
            self.close_open_field();
            return;
        }
        self.close_open_field();
        self.field_macros.entry(key.clone()).or_default();
        self.open_field = Some(key);
    }

    /// Close just the nested field-macro editor, keeping the parent LFO
    /// editor open. The inner half of Esc/`v`'s one-level-at-a-time close.
    pub(crate) fn close_open_field(&mut self) {
        let Some(key) = self.open_field.take() else {
            return;
        };
        if self
            .field_macros
            .get(&key)
            .is_some_and(|route| route.is_neutral())
        {
            self.field_macros.remove(&key);
        }
    }

    pub(crate) fn field_macro(&self, key: &str) -> Option<&MacroRoute> {
        self.field_macros.get(key)
    }

    pub(crate) fn field_macro_mut(&mut self, key: &str) -> Option<&mut MacroRoute> {
        self.field_macros.get_mut(key)
    }

    pub(crate) fn set_field_macro(&mut self, key: String, route: MacroRoute) {
        self.field_macros.insert(key, route);
    }

    /// Remove a stacked field macro outright (the x gesture on its nested
    /// row), closing it if it was the one expanded for editing.
    pub(crate) fn remove_field_macro(&mut self, key: &str) {
        self.field_macros.remove(key);
        if self.open_field.as_deref() == Some(key) {
            self.open_field = None;
        }
    }

    pub(crate) fn field_macros(&self) -> impl Iterator<Item = (&str, &MacroRoute)> {
        self.field_macros.iter().map(|(k, v)| (k.as_str(), v))
    }

    pub(crate) fn is_editor_open(&self) -> bool {
        self.open.is_some()
    }

    pub(crate) fn active_address(&self) -> Option<ControlAddress> {
        self.open.map(|open| open.address)
    }

    pub(crate) fn active_kind(&self) -> Option<ModKind> {
        self.open.map(|open| open.kind)
    }

    pub(crate) fn route(&self, address: ControlAddress) -> Option<&LfoRoute> {
        self.routes.get(&address)
    }

    pub(crate) fn route_mut(&mut self, address: ControlAddress) -> Option<&mut LfoRoute> {
        self.routes.get_mut(&address)
    }

    pub(crate) fn set_route(&mut self, address: ControlAddress, route: LfoRoute) {
        self.routes.insert(address, route);
    }

    pub(crate) fn routes(&self) -> impl Iterator<Item = (ControlAddress, &LfoRoute)> {
        self.routes.iter().map(|(address, route)| (*address, route))
    }

    pub(crate) fn envelope(&self, address: ControlAddress) -> Option<&EnvelopeRoute> {
        self.envelopes.get(&address)
    }

    pub(crate) fn envelope_mut(&mut self, address: ControlAddress) -> Option<&mut EnvelopeRoute> {
        self.envelopes.get_mut(&address)
    }

    pub(crate) fn set_envelope(&mut self, address: ControlAddress, route: EnvelopeRoute) {
        self.envelopes.insert(address, route);
    }

    pub(crate) fn macro_route(&self, address: ControlAddress) -> Option<&MacroRoute> {
        self.macros.get(&address)
    }

    pub(crate) fn macro_route_mut(&mut self, address: ControlAddress) -> Option<&mut MacroRoute> {
        self.macros.get_mut(&address)
    }

    pub(crate) fn set_macro_route(&mut self, address: ControlAddress, route: MacroRoute) {
        self.macros.insert(address, route);
    }

    pub(crate) fn macro_routes(&self) -> impl Iterator<Item = (ControlAddress, &MacroRoute)> {
        self.macros.iter().map(|(address, route)| (*address, route))
    }

    pub(crate) fn envelopes(&self) -> impl Iterator<Item = (ControlAddress, &EnvelopeRoute)> {
        self.envelopes
            .iter()
            .map(|(address, route)| (*address, route))
    }

    fn modulated_addresses(&self) -> BTreeSet<ControlAddress> {
        self.routes
            .keys()
            .chain(self.envelopes.keys())
            .chain(self.macros.keys())
            .copied()
            .collect()
    }

    /// Morphed automation state for a leg transition between `from` and `to`,
    /// the `AutomationState` counterpart to `MorphState::controls_at`'s
    /// per-`FluidControls`-field glide/snap split: `tt` (0..1) is the glide
    /// fraction for each route's level field (`LfoRoute::depth_ratio`,
    /// `EnvelopeRoute::amount`, every `MacroRoute` amount), and `use_to`
    /// selects which side's other fields (shape, cycle, attack/decay,
    /// trigger, …) are live — false holds `from`'s, true snaps to `to`'s, all
    /// together at the transition downbeat, mirroring
    /// `STRUCTURAL_SNAP_IDS`. A route present on only one side fades in or
    /// out via the level field rather than popping, and never needs explicit
    /// removal: once this leg's `to` becomes the next leg's `from`, an
    /// absent route is simply absent from the map again. Editor-open state
    /// (`open`, `open_field`) is UI navigation, not audible, and is never
    /// morphed — the result always has neither open.
    pub(crate) fn morph(
        from: &AutomationState,
        to: &AutomationState,
        tt: f32,
        use_to: bool,
    ) -> AutomationState {
        let mut result = AutomationState::default();
        morph_map(&from.routes, &to.routes, &mut result.routes, |f, t| {
            LfoRoute::morph(f, t, tt, use_to)
        });
        morph_map(
            &from.envelopes,
            &to.envelopes,
            &mut result.envelopes,
            |f, t| EnvelopeRoute::morph(f, t, tt, use_to),
        );
        morph_map(&from.macros, &to.macros, &mut result.macros, |f, t| {
            MacroRoute::morph(f, t, tt)
        });
        morph_map(
            &from.field_macros,
            &to.field_macros,
            &mut result.field_macros,
            |f, t| MacroRoute::morph(f, t, tt),
        );
        result
    }
}

/// Merge two route maps across a leg transition: build the union of both
/// sides' keys (kept in sorted order via `BTreeSet`, matching the previous
/// per-map key-collection loops), then insert `morph(from, to)` for each key
/// that yields a route. A key absent from the result (both morph inputs
/// `None`, or `morph` returning `None`) is simply left out — this is how a
/// route naturally disappears once both legs' endpoints lack it.
fn morph_map<K: Ord + Clone, V>(
    from: &BTreeMap<K, V>,
    to: &BTreeMap<K, V>,
    out: &mut BTreeMap<K, V>,
    morph: impl Fn(Option<&V>, Option<&V>) -> Option<V>,
) {
    let keys: BTreeSet<&K> = from.keys().chain(to.keys()).collect();
    for key in keys {
        if let Some(route) = morph(from.get(key), to.get(key)) {
            out.insert(key.clone(), route);
        }
    }
}

/// The effective value the engine plays for a modulated control: base plus
/// LFO plus envelope plus macro, summed, clamped to range, then snapped per
/// the control's `LfoSnap`. `macro_mod` carries `(route amount, live macro
/// value)`. The UI's modulation marker must go through this too so it shows
/// what is heard.
pub(crate) fn modulated_control_value_full(
    spec: &ControlSpec,
    lfo: Option<&LfoRoute>,
    envelope: Option<&EnvelopeRoute>,
    macro_mod: Option<f32>,
    base: f32,
    ctx: ModContext,
) -> f32 {
    let range = spec.max - spec.min;
    let mut value = base;
    if let Some(route) = lfo {
        value += route.wave_at(ctx.beat) * range * route.depth_ratio.clamp(0.0, 1.0);
    }
    if let Some(route) = envelope {
        value += route.level_at(ctx) * range * route.amount.clamp(-1.0, 1.0);
    }
    if let Some(combined) = macro_mod {
        value += combined * range;
    }
    let value = value.clamp(spec.min, spec.max);
    match spec.lfo_snap {
        LfoSnap::None => value,
        LfoSnap::PowerOfTwo => nearest_power_of_two(value, spec.min, spec.max),
        LfoSnap::Step => spec.quantize(value),
    }
}

/// LFO-only convenience wrapper over `modulated_control_value_full`.
#[cfg(test)]
pub(crate) fn modulated_control_value(
    spec: &ControlSpec,
    route: &LfoRoute,
    base: f32,
    beat: f64,
) -> f32 {
    modulated_control_value_full(
        spec,
        Some(route),
        None,
        None,
        base,
        ModContext::lfo_only(beat),
    )
}

/// Combined contribution of every macro slider a route rides, or None when
/// the route is neutral (every slot at zero). Reads the macro sliders from
/// `controls`, so callers that want their own modulation reflected must
/// apply it to `controls` first (`apply_automation` pass one does).
fn macro_pair(route: &MacroRoute, controls: &FluidControls) -> Option<f32> {
    if route.is_neutral() {
        return None;
    }
    Some(route.combined(&controls.macros.values))
}

/// UI-side variant: recomputes each ridden macro slider's own modulated
/// value from raw controls, mirroring what `apply_automation` pass one
/// produces, so markers show what the engine hears.
fn live_macro_pair(
    route: &MacroRoute,
    automation: &AutomationState,
    controls: &FluidControls,
    ctx: ModContext,
) -> Option<f32> {
    if route.is_neutral() {
        return None;
    }
    let mut values = [0.0; MACRO_COUNT];
    for (i, value) in values.iter_mut().enumerate() {
        if route.amounts[i].abs() <= f32::EPSILON {
            continue;
        }
        let spec = spec_by_id(MACRO_CONTROLS[i].id).expect("macro sliders are registered controls");
        let macro_address = ControlAddress::new(spec.id);
        *value = modulated_control_value_full(
            spec,
            automation
                .route(macro_address)
                .filter(|route| route.depth_ratio > f32::EPSILON),
            automation
                .envelope(macro_address)
                .filter(|route| route.amount.abs() > f32::EPSILON),
            None,
            (spec.get)(controls),
            ctx,
        );
    }
    Some(route.combined(&values))
}

pub(crate) fn live_macro_contribution(
    automation: &AutomationState,
    controls: &FluidControls,
    address: ControlAddress,
    ctx: ModContext,
) -> Option<f32> {
    let route = automation.macro_route(address)?;
    live_macro_pair(route, automation, controls, ctx)
}

/// Slot order for stacked LFO field macros, shared by every fold over them
/// (`PlannedRoute::field_macros` uses the same indices).
const LFO_FIELD_MACRO_SLOTS: [LfoField; 3] =
    [LfoField::Amount, LfoField::Interval, LfoField::Offset];

/// Fold per-slot combined macro ratios into a modulated copy of the route.
/// `contribution(slot)` resolves the stacked macro on `LFO_FIELD_MACRO_SLOTS[slot]`,
/// or None when there is none / it is neutral.
fn fold_field_macro_contributions(
    route: &LfoRoute,
    mut contribution: impl FnMut(usize) -> Option<f32>,
) -> LfoRoute {
    let mut effective = *route;
    if let Some(combined) = contribution(0) {
        effective.depth_ratio = (route.depth_ratio + combined).clamp(0.0, 1.0);
    }
    if let Some(combined) = contribution(1) {
        effective.cycle_beats = (route.cycle_beats
            + combined * (MAX_LFO_CYCLE_BEATS - MIN_LFO_CYCLE_BEATS))
            .clamp(MIN_LFO_CYCLE_BEATS, MAX_LFO_CYCLE_BEATS);
    }
    if let Some(combined) = contribution(2) {
        effective.phase_offset_beats = (route.phase_offset_beats + combined * MAX_LFO_OFFSET_BEATS)
            .clamp(0.0, MAX_LFO_OFFSET_BEATS);
    }
    effective
}

/// Fold any macros stacked onto an LFO route's amount/interval/offset (via
/// the field editor's `v` gesture) into a modulated copy, using whatever
/// `contribution` resolves each stacked field-macro's combined ratio to.
/// A macro slider's own LFO never takes a stacked macro (no macro chasing
/// itself), so this is a no-op there.
fn apply_field_macros(
    automation: &AutomationState,
    address: ControlAddress,
    route: &LfoRoute,
    mut contribution: impl FnMut(&MacroRoute) -> Option<f32>,
) -> LfoRoute {
    if is_macro_id(address.id()) {
        return *route;
    }
    fold_field_macro_contributions(route, |slot| {
        let key = unit_key(address.id(), LFO_FIELD_MACRO_SLOTS[slot].macro_key());
        automation.field_macro(&key).and_then(&mut contribution)
    })
}

/// Engine-side semantics (`AutomationPlan::apply` is the production copy):
/// `controls` already reflects pass-one's modulated macro slider values,
/// so a plain lookup is correct.
#[cfg(test)]
pub(crate) fn effective_lfo_route(
    automation: &AutomationState,
    controls: &FluidControls,
    address: ControlAddress,
    route: &LfoRoute,
) -> LfoRoute {
    apply_field_macros(automation, address, route, |field_route| {
        macro_pair(field_route, controls)
    })
}

/// UI-side twin: recomputes each stacked macro's own live modulation so the
/// parent slider's markers show what the engine hears.
pub(crate) fn live_effective_lfo_route(
    automation: &AutomationState,
    controls: &FluidControls,
    address: ControlAddress,
    route: &LfoRoute,
    ctx: ModContext,
) -> LfoRoute {
    apply_field_macros(automation, address, route, |field_route| {
        live_macro_pair(field_route, automation, controls, ctx)
    })
}

/// One modulated control's routes, resolved to plain copies so applying
/// them per sample needs no map lookups, string keys, or heap.
struct PlannedRoute {
    spec: &'static ControlSpec,
    lfo: Option<LfoRoute>,
    /// Stacked field macros indexed by `LFO_FIELD_MACRO_SLOTS`.
    field_macros: [Option<MacroRoute>; 3],
    envelope: Option<EnvelopeRoute>,
    macro_route: Option<MacroRoute>,
}

/// Allocation-free application plan for an `AutomationState`. The engine
/// rebuilds it only when the published automation Arc changes (a UI edit),
/// so the per-sample audio hot path never touches the allocator.
#[derive(Default)]
pub(crate) struct AutomationPlan {
    /// Macro sliders first, so targets read already-modulated macro values.
    routes: Vec<PlannedRoute>,
}

impl AutomationPlan {
    pub(crate) fn rebuild(&mut self, automation: &AutomationState) {
        self.routes.clear();
        let addresses = automation.modulated_addresses();
        let (macro_sliders, targets): (Vec<_>, Vec<_>) = addresses
            .into_iter()
            .partition(|address| is_macro_id(address.id()));
        for address in macro_sliders.into_iter().chain(targets) {
            let lfo = automation.route(address).copied();
            // Macro sliders' own LFOs never take a stacked macro.
            let field_macros = if lfo.is_none() || is_macro_id(address.id()) {
                [None; 3]
            } else {
                LFO_FIELD_MACRO_SLOTS.map(|field| {
                    let key = unit_key(address.id(), field.macro_key());
                    automation.field_macro(&key).copied()
                })
            };
            self.routes.push(PlannedRoute {
                spec: address.spec(),
                lfo,
                field_macros,
                envelope: automation.envelope(address).copied(),
                macro_route: automation.macro_route(address).copied(),
            });
        }
    }

    pub(crate) fn apply(&self, controls: &mut FluidControls, timing: TimingContext) {
        let ctx = ModContext {
            beat: timing.beat,
            kick_interval_beats: controls.kick.interval_beats,
            kick_offset_beats: controls.kick.offset_beats,
        };
        for planned in &self.routes {
            let lfo = planned.lfo.map(|route| {
                fold_field_macro_contributions(&route, |slot| {
                    planned.field_macros[slot]
                        .as_ref()
                        .and_then(|field_route| macro_pair(field_route, controls))
                })
            });
            let lfo = lfo
                .as_ref()
                .filter(|route| route.depth_ratio > f32::EPSILON);
            let envelope = planned
                .envelope
                .as_ref()
                .filter(|route| route.amount.abs() > f32::EPSILON);
            let macro_mod = planned
                .macro_route
                .as_ref()
                .and_then(|route| macro_pair(route, controls));
            if lfo.is_none() && envelope.is_none() && macro_mod.is_none() {
                continue;
            }
            let base = (planned.spec.get)(controls);
            let value =
                modulated_control_value_full(planned.spec, lfo, envelope, macro_mod, base, ctx);
            (planned.spec.set)(controls, value);
        }
    }
}

/// One-shot convenience over `AutomationPlan` for tests: rebuild + apply.
#[cfg(test)]
pub(crate) fn apply_automation(
    controls: &mut FluidControls,
    automation: &AutomationState,
    timing: TimingContext,
) {
    let mut plan = AutomationPlan::default();
    plan.rebuild(automation);
    plan.apply(controls, timing);
}