bevy_director 0.7.0-dev

Unreal-Sequencer-inspired cinematic camera and sequence system for Bevy
Documentation
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
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
//! The runtime: who renders, when, and what the camera does about it.
//! One state machine (DirectorState.phase): Idle until asked, Shooting
//! while a sequence owns the frame, Handback while it glides to the live
//! camera, Viewfinder while a human flies. All mutation happens in
//! PostUpdate before transform propagation, so a pose written this frame
//! renders this frame.

use bevy::{
    camera::Exposure,
    core_pipeline::prepass::MotionVectorPrepass,
    post_process::{
        dof::{DepthOfField, DepthOfFieldMode},
        effect_stack::{ChromaticAberration, LensDistortion, Vignette},
        motion_blur::MotionBlur,
    },
    prelude::*,
    render::view::ColorGrading,
};

use crate::{
    eval::{
        ActiveActorCue, ActiveText, CameraPose, CameraSnapshot, CompiledSequence, EvalCtx, bake,
        mix,
    },
    letterbox::LetterboxSettings,
    sequence::{Blend, SequenceAsset},
};

/// The optional dedicated camera. Spawn your own and the director adopts
/// it for every take; without one the director borrows the gameplay
/// camera and drives it in place, so clear color, tonemapping, bloom,
/// and the rest of your post stack are never swapped out from under the
/// frame. The marker rides the borrowed camera for the length of a take.
#[derive(Component, Default)]
pub struct CineCamera;

/// Optional marker naming the gameplay camera to hand off from and back
/// to, for apps with several non-cine cameras. With exactly one active
/// camera the director finds it by itself.
#[derive(Component)]
pub struct HandoffCamera;

/// Playback state for a sequence, on the cine camera entity.
#[derive(Component)]
pub struct SequencePlayer {
    pub sequence: Handle<SequenceAsset>,
    pub playhead: f32,
    pub rate: f32,
    pub playback: Playback,
    pub clock: ClockSource,
    pub loop_mode: LoopMode,
}

impl SequencePlayer {
    pub fn new(sequence: Handle<SequenceAsset>) -> Self {
        Self {
            sequence,
            playhead: 0.0,
            rate: 1.0,
            playback: Playback::Playing,
            clock: ClockSource::default(),
            loop_mode: LoopMode::default(),
        }
    }

    /// Jump the playhead. Seeks never fire markers.
    pub fn seek(&mut self, t: f32) {
        self.playhead = t.max(0.0);
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Playback {
    Stopped,
    #[default]
    Playing,
    Paused,
}

/// Which clock advances the playhead. Virtual freezes with the game's
/// pause; Real keeps rolling through it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ClockSource {
    #[default]
    Virtual,
    Real,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LoopMode {
    #[default]
    Once,
    Loop,
    /// Bounce between the ends, flipping the rate.
    PingPong,
}

/// What the director is doing right now. A plain resource: map it onto
/// your own game states however you like.
#[derive(Resource, Default)]
pub struct DirectorState {
    pub phase: DirectorPhase,
    /// The camera on air right now: the take's anchor, or whichever
    /// named [`CineCamera`] the current shot cut to. Titles and the
    /// letterbox follow this one.
    pub camera: Option<Entity>,
    /// Where the take's playback lives — resolved when it started and
    /// never moved by a cut. Equal to `camera` outside a cut.
    pub anchor: Option<Entity>,
    /// The gameplay camera the director took the frame from.
    pub live_camera: Option<Entity>,
}

impl DirectorState {
    /// True while the gameplay camera is the one being driven, rather
    /// than a separate cine camera it handed the frame to.
    pub fn is_borrowing(&self) -> bool {
        self.anchor.is_some() && self.anchor == self.live_camera
    }

    /// The camera carrying the take's playback state. Falls back to
    /// `camera` for apps that drive [`DirectorState`] by hand.
    pub fn take_anchor(&self) -> Option<Entity> {
        self.anchor.or(self.camera)
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum DirectorPhase {
    #[default]
    Idle,
    Shooting,
    Handback,
    Viewfinder,
}

/// The text blocks visible this frame, fades resolved, refreshed during
/// [`DirectorSet::Apply`](crate::DirectorSet); empty whenever nothing is
/// on. This is the whole contract for custom caption rendering: read it
/// and draw. The `titles` feature ships a built-in renderer over the
/// same data.
#[derive(Resource, Default, Debug, Clone)]
pub struct ActiveTexts {
    pub blocks: Vec<ActiveText>,
}

/// The actor cues the playhead is inside this frame, weights resolved,
/// refreshed during [`DirectorSet::Apply`](crate::DirectorSet); empty
/// whenever no take runs. This is the whole actor-track contract: the
/// game reads it, matches each cue's `Entity(name)` target against its
/// own entities, and drives its own animation setup — deriving start and
/// stop edges from the stable `(track, cue_index)` pair. There are
/// deliberately no per-cue messages: a level-triggered resource survives
/// seeks, skips, loops, and reverse playback with no cursor bookkeeping.
#[derive(Resource, Default, Debug, Clone)]
pub struct ActiveActorCues {
    pub cues: Vec<ActiveActorCue>,
}

/// Run condition: no directed camera work at all.
pub fn director_idle(state: Res<DirectorState>) -> bool {
    state.phase == DirectorPhase::Idle
}

/// Run condition: a sequence or the viewfinder owns the frame.
pub fn director_active(state: Res<DirectorState>) -> bool {
    state.phase != DirectorPhase::Idle
}

/// Run condition for the game's own camera-driving system: true while the
/// gameplay camera should keep moving. That includes Handback, where the
/// director chases the live camera, so keep your rig running under this.
///
/// This is for games with their own [`CineCamera`]. When the director
/// borrows the gameplay camera there is nothing to chase — it glides
/// back to the pose it took over — so a rig writing that same transform
/// through Handback fights the blend; gate those on [`director_idle`].
pub fn gameplay_camera_free(state: Res<DirectorState>) -> bool {
    matches!(state.phase, DirectorPhase::Idle | DirectorPhase::Handback)
}

// ---------- messages ----------

/// A sequence took the frame. `camera` is the take's anchor, which is
/// stable across cuts; [`SequenceCut`] reports the camera on air.
#[derive(Message, Debug, Clone)]
pub struct SequenceStarted {
    pub camera: Entity,
    pub sequence: AssetId<SequenceAsset>,
}

/// The take cut to a different camera. Stingers, rumble, and anything
/// else that should land on the cut belong here.
#[derive(Message, Debug, Clone)]
pub struct SequenceCut {
    pub from: Entity,
    pub to: Entity,
    /// The shot that owns the playhead after the cut.
    pub shot: usize,
}

/// The playhead crossed a marker while playing forward.
#[derive(Message, Debug, Clone)]
pub struct MarkerReached {
    pub camera: Entity,
    pub name: String,
    pub time: f32,
}

/// The sequence gave the frame back (or is about to glide it back).
#[derive(Message, Debug, Clone)]
pub struct SequenceFinished {
    pub camera: Entity,
    pub reason: FinishReason,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum FinishReason {
    Completed,
    Skipped,
    Stopped,
}

/// Internal control-channel messages, written by DirectorCommands.
#[derive(Message)]
pub(crate) enum DirectorRequest {
    Play {
        handle: Handle<SequenceAsset>,
        options: PlayOptions,
    },
    Skip,
    Stop,
}

/// Tuning for one playback.
#[derive(Clone, Debug)]
pub struct PlayOptions {
    pub rate: f32,
    pub clock: ClockSource,
    pub loop_mode: LoopMode,
    /// Overrides the asset's blend_out when set.
    pub blend_out: Option<Blend>,
    /// Crop the take to this aspect (e.g. 2.39 for scope) with real
    /// letterbox bars; cleared when the take ends.
    pub letterbox: Option<f32>,
}

impl Default for PlayOptions {
    fn default() -> Self {
        Self {
            rate: 1.0,
            clock: ClockSource::default(),
            loop_mode: LoopMode::default(),
            blend_out: None,
            letterbox: None,
        }
    }
}

/// Fire-and-forget control surface on Commands.
pub trait DirectorCommands {
    fn play_sequence(&mut self, handle: Handle<SequenceAsset>);
    fn play_sequence_with(&mut self, handle: Handle<SequenceAsset>, options: PlayOptions);
    /// Jump to the end and take the normal blend_out home.
    fn skip_sequence(&mut self);
    /// Hard stop: instant swap back to the live camera.
    fn stop_sequence(&mut self);
}

impl DirectorCommands for Commands<'_, '_> {
    fn play_sequence(&mut self, handle: Handle<SequenceAsset>) {
        self.play_sequence_with(handle, PlayOptions::default());
    }

    fn play_sequence_with(&mut self, handle: Handle<SequenceAsset>, options: PlayOptions) {
        self.queue(move |world: &mut World| {
            world.write_message(DirectorRequest::Play { handle, options });
        });
    }

    fn skip_sequence(&mut self) {
        self.queue(|world: &mut World| {
            world.write_message(DirectorRequest::Skip);
        });
    }

    fn stop_sequence(&mut self) {
        self.queue(|world: &mut World| {
            world.write_message(DirectorRequest::Stop);
        });
    }
}

// ---------- internal components ----------

/// The compiled sequence and the live-camera snapshot it blends from.
#[derive(Component)]
pub(crate) struct Baked {
    pub(crate) compiled: CompiledSequence,
    pub(crate) live: CameraSnapshot,
    /// Marker cursor: starts just below zero so a t=0 marker fires.
    pub(crate) marker_cursor: f32,
    pub(crate) blend_out: Option<Blend>,
    /// The last pose applied: feeds damped looks and seeds the handback.
    pub(crate) last_pose: Option<CameraPose>,
    /// Which lens components the director currently owns on the camera.
    pub(crate) lens_active: LensTouch,
    /// A softened held camera's smoothed world rotation, chased frame to
    /// frame. Cleared on a cut so it never slerps across mounts.
    pub(crate) held_rot: Option<Quat>,
    /// Camera names a cut could not resolve, so the warning is said
    /// once instead of every frame the shot is on screen.
    pub(crate) warned_cameras: Vec<String>,
}

/// Which lens components a take is driving. The director only issues
/// commands for the ones a shot actually uses, and a component the pose
/// just dropped still needs its one frame of removal.
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
pub(crate) struct LensTouch {
    dof: bool,
    exposure: bool,
    vignette: bool,
    distortion: bool,
    aberration: bool,
    motion_blur: bool,
    grading: bool,
}

impl LensTouch {
    pub(crate) fn of(pose: &CameraPose) -> Self {
        Self {
            dof: pose.dof.is_some(),
            exposure: pose.exposure_ev100.is_some(),
            vignette: pose.vignette.is_some(),
            distortion: pose.distortion.is_some(),
            aberration: pose.aberration.is_some(),
            motion_blur: pose.motion_blur.is_some(),
            grading: pose.grading.is_some(),
        }
    }

    pub(crate) fn union(self, other: Self) -> Self {
        Self {
            dof: self.dof || other.dof,
            exposure: self.exposure || other.exposure,
            vignette: self.vignette || other.vignette,
            distortion: self.distortion || other.distortion,
            aberration: self.aberration || other.aberration,
            motion_blur: self.motion_blur || other.motion_blur,
            grading: self.grading || other.grading,
        }
    }
}

/// A play request waiting for its asset to finish loading.
#[derive(Component)]
pub(crate) struct PendingPlay {
    handle: Handle<SequenceAsset>,
    options: PlayOptions,
}

/// The glide home at the end: from a frozen pose toward the live camera,
/// sampled fresh every frame.
#[derive(Component)]
pub(crate) struct HandbackBlend {
    from: CameraPose,
    elapsed: f32,
    blend: Blend,
    clock: ClockSource,
}

/// Everything the director will touch on the take camera, copied off
/// before the first pose lands and put back when the take ends. It lives
/// on the camera rather than in [`DirectorState`] so a mid-take despawn
/// takes the restore data with it instead of leaving it stale.
#[derive(Component)]
pub(crate) struct PreTakeState {
    transform: Transform,
    /// The whole projection, not just the fov: letterboxing writes
    /// `aspect_ratio` too.
    projection: Projection,
    viewport: Option<bevy::camera::Viewport>,
    dof: Option<DepthOfField>,
    exposure: Option<Exposure>,
    vignette: Option<Vignette>,
    distortion: Option<LensDistortion>,
    aberration: Option<ChromaticAberration>,
    motion_blur: Option<MotionBlur>,
    /// MotionBlur requires a MotionVectorPrepass, which bevy inserts for
    /// us but never takes back; the restore has to know whether the
    /// prepass was the game's to begin with.
    had_motion_vector_prepass: bool,
    /// The grade the take composes onto, and puts back untouched.
    grading: Option<ColorGrading>,
    role: TakeRole,
}

/// What a camera is to the take, which decides how much of it is owed
/// back when the take ends.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum TakeRole {
    /// The gameplay camera, driven in place: it gets its pose back, and
    /// the [`CineCamera`] marker the director stamped on comes off.
    Borrowed,
    /// A camera the game dedicated to the director. It keeps its last
    /// pose, the way the viewfinder leaves it parked where you flew it.
    Dedicated,
    /// A camera a cut visits. The game placed it and may use it for its
    /// own shots, so the take puts it back where it found it.
    CutTarget,
}

impl PreTakeState {
    /// The grade the camera had before the take, for composing onto.
    /// The previews reach for this; the runtime reads the field.
    #[cfg(feature = "viewfinder")]
    pub(crate) fn grading(&self) -> Option<&ColorGrading> {
        self.grading.as_ref()
    }

    /// The camera's own parked pose, for Held rigs in the previews.
    #[cfg(feature = "viewfinder")]
    pub(crate) fn held_snapshot(&self) -> CameraSnapshot {
        snapshot_of(&self.transform, Some(&self.projection))
    }
}

/// Snapshot the camera state a take is about to overwrite. Borrowing
/// also stamps the [`CineCamera`] marker, which is what lets every
/// `With<CineCamera>` query downstream stay as it was.
pub(crate) fn begin_take(role: TakeRole) -> impl EntityCommand {
    move |mut entity: EntityWorldMut| {
        let borrowed = role == TakeRole::Borrowed;
        let saved = PreTakeState {
            transform: entity.get::<Transform>().copied().unwrap_or_default(),
            projection: entity.get::<Projection>().cloned().unwrap_or_default(),
            viewport: entity.get::<Camera>().and_then(|c| c.viewport.clone()),
            dof: entity.get::<DepthOfField>().cloned(),
            exposure: entity.get::<Exposure>().cloned(),
            vignette: entity.get::<Vignette>().cloned(),
            distortion: entity.get::<LensDistortion>().cloned(),
            aberration: entity.get::<ChromaticAberration>().cloned(),
            motion_blur: entity.get::<MotionBlur>().cloned(),
            had_motion_vector_prepass: entity.contains::<MotionVectorPrepass>(),
            grading: entity.get::<ColorGrading>().cloned(),
            role,
        };
        if borrowed && entity.contains::<ChildOf>() {
            warn!(
                "the gameplay camera is parented; directed poses are world space and will \
                 fight its parent. Spawn a CineCamera entity for this game."
            );
        }
        entity.insert(saved);
        if borrowed {
            entity.insert(CineCamera);
        }
    }
}

/// Put back everything [`begin_take`] saved and strip the playback
/// components. Without a `PreTakeState` (a camera the director never
/// captured, e.g. one an app drives through `DirectorState` by hand)
/// this is just the strip.
fn end_take(mut entity: EntityWorldMut) {
    entity.remove::<(
        SequencePlayer,
        Baked,
        HandbackBlend,
        PendingPlay,
        SkipRequested,
        LetterboxSettings,
    )>();
    let Some(saved) = entity.take::<PreTakeState>() else {
        // Nothing captured: the lens components are still the director's.
        // The motion vector prepass stays — on a camera we never looked
        // at, we cannot tell ours from the game's, and an extra prepass
        // only costs time where a wrong removal breaks its rendering.
        entity.remove::<(
            DepthOfField,
            Exposure,
            Vignette,
            LensDistortion,
            ChromaticAberration,
            MotionBlur,
            ColorGrading,
        )>();
        return;
    };
    if let Some(mut camera) = entity.get_mut::<Camera>() {
        camera.viewport = saved.viewport;
    }
    if let Some(mut projection) = entity.get_mut::<Projection>() {
        *projection = saved.projection;
    }
    restore_component(&mut entity, saved.dof);
    restore_component(&mut entity, saved.exposure);
    restore_component(&mut entity, saved.vignette);
    restore_component(&mut entity, saved.distortion);
    restore_component(&mut entity, saved.aberration);
    restore_component(&mut entity, saved.motion_blur);
    restore_component(&mut entity, saved.grading);
    if !saved.had_motion_vector_prepass {
        entity.remove::<MotionVectorPrepass>();
    }
    if saved.role != TakeRole::Dedicated {
        entity.insert(saved.transform);
    }
    if saved.role == TakeRole::Borrowed {
        entity.remove::<CineCamera>();
    }
}

/// Put a captured component back, or take ours off when the camera had
/// none of its own.
fn restore_component<C: Component>(entity: &mut EntityWorldMut, saved: Option<C>) {
    match saved {
        Some(component) => {
            entity.insert(component);
        }
        None => {
            entity.remove::<C>();
        }
    }
}

// ---------- systems ----------

pub(crate) fn snapshot_of(
    transform: &Transform,
    projection: Option<&Projection>,
) -> CameraSnapshot {
    let fov_y = match projection {
        Some(Projection::Perspective(p)) => p.fov,
        _ => 45f32.to_radians(),
    };
    CameraSnapshot {
        position: transform.translation,
        rotation: transform.rotation,
        fov_y,
    }
}

/// Find the gameplay camera to hand off from: prefer HandoffCamera, else
/// the unique active non-cine 3D camera.
fn resolve_live_camera(
    cameras: &Query<(Entity, &Camera, Has<HandoffCamera>), (With<Camera3d>, Without<CineCamera>)>,
) -> Option<Entity> {
    if let Some((e, ..)) = cameras.iter().find(|(_, _, marked)| *marked) {
        return Some(e);
    }
    let mut actives = cameras.iter().filter(|(_, cam, _)| cam.is_active);
    let first = actives.next().map(|(e, ..)| e);
    if actives.next().is_some() {
        warn!("several active cameras and no HandoffCamera marker; picking one arbitrarily");
    }
    first
}

/// Spawn a cine camera from nothing. Only reached when the app has no
/// camera at all to borrow and none marked CineCamera, so it is bare
/// bones by definition. The active flag rides the bundle because a
/// same-frame get_mut cannot see an entity whose commands have not
/// flushed yet.
fn spawn_fallback_cine_camera(commands: &mut Commands, active: bool) -> Entity {
    commands
        .spawn((
            Name::new("cine camera"),
            CineCamera,
            Camera3d::default(),
            Camera {
                is_active: active,
                ..Default::default()
            },
            Projection::default(),
            Transform::default(),
        ))
        .id()
}

/// Drain control requests. Play resolves cameras, bakes (or parks a
/// PendingPlay until the asset arrives), snapshots the live pose, and
/// swaps is_active in this one place so the two flags never disagree.
#[allow(clippy::too_many_arguments)] // the control hub touches everything
pub(crate) fn handle_requests(
    mut commands: Commands,
    mut requests: MessageReader<DirectorRequest>,
    mut state: ResMut<DirectorState>,
    assets: Res<Assets<SequenceAsset>>,
    // p0 reads cameras to pick the live one; p1 writes is_active. A
    // ParamSet because they overlap on Camera.
    mut cameras: ParamSet<(
        Query<(Entity, &Camera, Has<HandoffCamera>), (With<Camera3d>, Without<CineCamera>)>,
        Query<&mut Camera>,
    )>,
    cine_cameras: Query<(Entity, Option<&Name>), With<CineCamera>>,
    pending: Query<(Entity, &PendingPlay)>,
    mut players: Query<(&mut SequencePlayer, Option<&Baked>)>,
    transforms: Query<(&Transform, Option<&Projection>)>,
    mut started: MessageWriter<SequenceStarted>,
    mut finished: MessageWriter<SequenceFinished>,
) {
    // Retry a parked play once its asset shows up.
    let retry: Option<(Handle<SequenceAsset>, PlayOptions, Entity)> = pending
        .iter()
        .next()
        .filter(|(_, p)| assets.contains(&p.handle))
        .map(|(e, p)| (p.handle.clone(), p.options.clone(), e));
    let mut plays: Vec<(Handle<SequenceAsset>, PlayOptions)> = Vec::new();
    if let Some((handle, options, entity)) = retry {
        commands.entity(entity).remove::<PendingPlay>();
        plays.push((handle, options));
    }

    for request in requests.read() {
        match request {
            DirectorRequest::Play { handle, options } => {
                plays.push((handle.clone(), options.clone()));
            }
            DirectorRequest::Skip => {
                if state.phase == DirectorPhase::Shooting
                    && let Some(camera) = state.take_anchor()
                    && let Ok((mut player, baked)) = players.get_mut(camera)
                    && let Some(baked) = baked
                {
                    // Jump to the end; the tick system routes the finish.
                    player.playhead = baked.compiled.duration();
                    player.playback = Playback::Playing;
                    player.loop_mode = LoopMode::Once;
                    finished.write(SequenceFinished {
                        camera,
                        reason: FinishReason::Skipped,
                    });
                    commands.entity(camera).insert(SkipRequested);
                }
            }
            DirectorRequest::Stop => {
                if state.phase == DirectorPhase::Shooting || state.phase == DirectorPhase::Handback
                {
                    if let Some(camera) = state.take_anchor() {
                        finished.write(SequenceFinished {
                            camera,
                            reason: FinishReason::Stopped,
                        });
                    }
                    let mut writable = cameras.p1();
                    restore_live(&mut commands, &mut state, &mut writable);
                }
            }
        }
    }

    for (handle, options) in plays {
        if state.phase != DirectorPhase::Idle {
            warn!(
                "play_sequence ignored: the director is already {:?}",
                state.phase
            );
            continue;
        }
        let live_entity = resolve_live_camera(&cameras.p0());

        let Some(asset) = assets.get(&handle) else {
            // Not loaded yet: park the request wherever the take will
            // land, without claiming the camera. The retry re-resolves.
            let holder = cine_cameras
                .iter()
                .next()
                .map(|(e, _)| e)
                .or(live_entity)
                .unwrap_or_else(|| spawn_fallback_cine_camera(&mut commands, false));
            commands.entity(holder).insert(PendingPlay {
                handle: handle.clone(),
                options,
            });
            continue;
        };
        let compiled = match bake(asset) {
            Ok(compiled) => compiled,
            Err(err) => {
                error!("sequence '{}' failed to bake: {err}", asset.name);
                continue;
            }
        };

        // A cine camera the sequence cuts to is a destination, not the
        // take's own camera; anything else is a dedicated camera to
        // adopt. With none to adopt the gameplay camera is driven where
        // it stands, so its render settings never leave the frame. A
        // fresh fallback spawns already active because the swap below
        // can only reach cameras that exist.
        let existing = cine_cameras
            .iter()
            .find(|(_, name)| name.is_none_or(|name| !compiled.cuts_to(name.as_str())))
            .map(|(e, _)| e);
        let borrowed = existing.is_none() && live_entity.is_some();
        let cine = existing
            .or(live_entity)
            .unwrap_or_else(|| spawn_fallback_cine_camera(&mut commands, true));

        let live = live_entity
            .and_then(|e| transforms.get(e).ok())
            .map(|(t, p)| snapshot_of(t, p))
            .unwrap_or(CameraSnapshot {
                position: Vec3::ZERO,
                rotation: Quat::IDENTITY,
                fov_y: 45f32.to_radians(),
            });

        let blend_out = options.blend_out.or(compiled.blend_out());
        let mut cine_commands = commands.entity(cine);
        cine_commands.queue(begin_take(if borrowed {
            TakeRole::Borrowed
        } else {
            TakeRole::Dedicated
        }));
        cine_commands.insert((
            SequencePlayer {
                sequence: handle.clone(),
                playhead: 0.0,
                rate: options.rate,
                playback: Playback::Playing,
                clock: options.clock,
                loop_mode: options.loop_mode,
            },
            Baked {
                compiled,
                live,
                marker_cursor: -f32::EPSILON,
                blend_out,
                last_pose: None,
                lens_active: LensTouch::default(),
                held_rot: None,
                warned_cameras: Vec::new(),
            },
        ));
        if let Some(aspect) = options.letterbox {
            cine_commands.insert(LetterboxSettings { aspect });
        }

        // The swap: exactly one camera active, flipped together. A
        // borrowed camera is already the one on air.
        if !borrowed {
            let mut writable = cameras.p1();
            if let Some(live_entity) = live_entity
                && let Ok(mut cam) = writable.get_mut(live_entity)
            {
                cam.is_active = false;
            }
            if let Ok(mut cam) = writable.get_mut(cine) {
                cam.is_active = true;
            }
        }

        state.phase = DirectorPhase::Shooting;
        state.camera = Some(cine);
        state.anchor = Some(cine);
        state.live_camera = live_entity;
        started.write(SequenceStarted {
            camera: cine,
            sequence: handle.id(),
        });
    }
}

/// Skip was requested this frame; suppresses the Completed message when
/// the tick routes the finish.
#[derive(Component)]
pub(crate) struct SkipRequested;

/// Hot reload: rebake when the asset file changes under a live player.
pub(crate) fn rebake_on_asset_change(
    mut events: MessageReader<AssetEvent<SequenceAsset>>,
    assets: Res<Assets<SequenceAsset>>,
    mut players: Query<(&mut SequencePlayer, &mut Baked)>,
) {
    for event in events.read() {
        let AssetEvent::Modified { id } = event else {
            continue;
        };
        for (mut player, mut baked) in &mut players {
            if player.sequence.id() != *id {
                continue;
            }
            let Some(asset) = assets.get(*id) else {
                continue;
            };
            match bake(asset) {
                Ok(compiled) => {
                    player.playhead = player.playhead.min(compiled.duration());
                    baked.compiled = compiled;
                    info!("sequence '{}' rebaked from disk", asset.name);
                }
                Err(err) => error!("sequence '{}' failed to rebake: {err}", asset.name),
            }
        }
    }
}

/// If the cine camera (or its player) vanished mid-flight, put the live
/// camera back on air. This is what keeps a quit-to-title mid-cutscene
/// from black-screening the menu.
pub(crate) fn guard_orphans(
    mut commands: Commands,
    mut state: ResMut<DirectorState>,
    players: Query<&SequencePlayer>,
    mut cameras: Query<&mut Camera>,
    mut finished: MessageWriter<SequenceFinished>,
) {
    if state.phase == DirectorPhase::Idle {
        return;
    }
    // A cut target vanishing is survivable — the cut falls back to the
    // anchor — but losing the anchor loses the take.
    let camera_gone = if state.phase == DirectorPhase::Viewfinder {
        state.camera.is_none_or(|e| cameras.get(e).is_err())
    } else {
        state.take_anchor().is_none_or(|e| players.get(e).is_err())
    };
    if !camera_gone {
        return;
    }
    if let Some(camera) = state.take_anchor() {
        finished.write(SequenceFinished {
            camera,
            reason: FinishReason::Stopped,
        });
    }
    restore_live(&mut commands, &mut state, &mut cameras);
}

/// Back to Idle: the camera the take borrowed or was handed goes back to
/// what it was, playback components gone. Safe against despawned
/// entities on either side.
pub(crate) fn restore_live(
    commands: &mut Commands,
    state: &mut DirectorState,
    cameras: &mut Query<&mut Camera>,
) {
    // Only ever dark a cine camera in favour of a live one; otherwise a
    // take that had the only camera in the scene ends in black. A cut
    // may have left the borrowed anchor dark, so it is relit here too.
    if let Some(live) = state.live_camera {
        if let Ok(mut cam) = cameras.get_mut(live) {
            cam.is_active = true;
        }
        for cine in [state.camera, state.anchor].into_iter().flatten() {
            if cine != live
                && let Ok(mut cam) = cameras.get_mut(cine)
            {
                cam.is_active = false;
            }
        }
    }
    // Every camera the take touched carries its own PreTakeState, cut
    // targets included, and the query only yields the ones still alive.
    // The anchor joins them even without one, so a hand-driven
    // DirectorState still gets its playback components stripped.
    let anchor = state.take_anchor();
    commands.queue(move |world: &mut World| {
        let mut captured: Vec<Entity> = world
            .query_filtered::<Entity, With<PreTakeState>>()
            .iter(world)
            .collect();
        if let Some(anchor) = anchor
            && !captured.contains(&anchor)
        {
            captured.push(anchor);
        }
        for camera in captured {
            if let Ok(entity) = world.get_entity_mut(camera) {
                end_take(entity);
            }
        }
    });
    state.phase = DirectorPhase::Idle;
    state.camera = None;
    state.anchor = None;
    state.live_camera = None;
}

/// Advance playheads, fire markers, and route the end of the sequence
/// into a handback (or an instant swap when there is no blend_out).
pub(crate) fn tick_players(
    mut commands: Commands,
    mut state: ResMut<DirectorState>,
    virtual_time: Res<Time<Virtual>>,
    real_time: Res<Time<Real>>,
    mut players: Query<(Entity, &mut SequencePlayer, &mut Baked, Has<SkipRequested>)>,
    mut cameras: Query<&mut Camera>,
    mut markers: MessageWriter<MarkerReached>,
    mut finished: MessageWriter<SequenceFinished>,
) {
    if state.phase != DirectorPhase::Shooting {
        return;
    }
    let Some(camera) = state.take_anchor() else {
        return;
    };
    let Ok((entity, mut player, mut baked, skipping)) = players.get_mut(camera) else {
        return;
    };
    if player.playback != Playback::Playing {
        return;
    }
    // A take that ends while cut away has nothing to glide: the named
    // camera is not the one the game is getting back.
    let cut_away = state.camera != Some(camera);

    let dt = match player.clock {
        ClockSource::Virtual => virtual_time.delta_secs(),
        ClockSource::Real => real_time.delta_secs(),
    } * player.rate;
    player.playhead += dt;

    let duration = baked.compiled.duration();
    let cursor = baked.marker_cursor;

    if !skipping {
        let fire = |m: &crate::sequence::Marker, markers: &mut MessageWriter<MarkerReached>| {
            markers.write(MarkerReached {
                camera: entity,
                name: m.name.clone(),
                time: m.time,
            });
        };
        if dt >= 0.0 {
            for marker in baked.compiled.markers_between(cursor, player.playhead) {
                fire(marker, &mut markers);
            }
        } else {
            for marker in baked
                .compiled
                .markers_between_backward(player.playhead, cursor)
            {
                fire(marker, &mut markers);
            }
        }
    }
    baked.marker_cursor = player.playhead;

    let over = dt >= 0.0 && player.playhead >= duration;
    let under = dt < 0.0 && player.playhead <= 0.0;
    if !over && !under {
        return;
    }

    match player.loop_mode {
        LoopMode::Loop => {
            let wrapped = if over {
                // Tail markers fired above; fire the head range too.
                let wrapped = (player.playhead - duration).max(0.0);
                if !skipping {
                    for marker in baked.compiled.markers_between(-f32::EPSILON, wrapped) {
                        markers.write(MarkerReached {
                            camera: entity,
                            name: marker.name.clone(),
                            time: marker.time,
                        });
                    }
                }
                wrapped
            } else {
                (player.playhead + duration).clamp(0.0, duration)
            };
            player.playhead = wrapped;
            baked.marker_cursor = wrapped;
        }
        LoopMode::PingPong => {
            player.rate = -player.rate;
            player.playhead = if over {
                (2.0 * duration - player.playhead).clamp(0.0, duration)
            } else {
                (-player.playhead).clamp(0.0, duration)
            };
            baked.marker_cursor = player.playhead;
        }
        LoopMode::Once => {
            player.playhead = if over { duration } else { 0.0 };
            player.playback = Playback::Stopped;
            if !skipping {
                finished.write(SequenceFinished {
                    camera: entity,
                    reason: FinishReason::Completed,
                });
            }
            match baked.blend_out {
                Some(blend) if blend.secs > 0.0 && !cut_away => {
                    // Start the glide from the last pose actually shown.
                    let from = baked.last_pose.unwrap_or_else(|| {
                        baked
                            .compiled
                            .pose_at(player.playhead, &EvalCtx::still(&baked.live))
                    });
                    commands.entity(entity).insert(HandbackBlend {
                        from,
                        elapsed: 0.0,
                        blend,
                        clock: player.clock,
                    });
                    state.phase = DirectorPhase::Handback;
                }
                _ => restore_live(&mut commands, &mut state, &mut cameras),
            }
        }
    }
}

/// Put the shot's named camera on air. Runs before the pose lands, so
/// the cut, the frame it shows, and the letterbox crop all agree.
///
/// The take's playback never moves: only which camera renders does.
/// Cutting to a camera the world does not have holds the anchor rather
/// than cutting to black.
#[allow(clippy::too_many_arguments)] // a cut touches every camera-shaped thing
pub(crate) fn execute_cuts(
    mut commands: Commands,
    mut state: ResMut<DirectorState>,
    mut players: Query<(&SequencePlayer, &mut Baked)>,
    named: Query<(Entity, &Name), With<CineCamera>>,
    mut cameras: Query<&mut Camera>,
    letterbox: Query<&LetterboxSettings>,
    captured: Query<(), With<PreTakeState>>,
    mut cuts: MessageWriter<SequenceCut>,
) {
    if state.phase != DirectorPhase::Shooting {
        return;
    }
    let (Some(anchor), Some(current)) = (state.take_anchor(), state.camera) else {
        return;
    };
    let Ok((player, mut baked)) = players.get_mut(anchor) else {
        return;
    };

    let playhead = player.playhead;
    let wanted = baked.compiled.camera_at(playhead).map(str::to_owned);
    let mut target = match &wanted {
        None => anchor,
        Some(name) => match named.iter().find(|(_, n)| n.as_str() == name.as_str()) {
            Some((entity, _)) => entity,
            None => {
                if !baked.warned_cameras.iter().any(|seen| seen == name) {
                    baked.warned_cameras.push(name.clone());
                    warn!(
                        "shot at {playhead:.2}s cuts to CineCamera '{name}', which no entity \
                         carries; staying on the take's camera"
                    );
                }
                anchor
            }
        },
    };
    // A cut target that despawned mid-shot must not take the frame down
    // with it.
    if target != anchor && cameras.get(target).is_err() {
        target = anchor;
    }
    if target == current {
        return;
    }

    // A camera the take has not used yet keeps its own settings: capture
    // them before the pose and lens land on it.
    if !captured.contains(target) {
        commands
            .entity(target)
            .queue(begin_take(TakeRole::CutTarget));
    }
    if let Ok(mut cam) = cameras.get_mut(current) {
        cam.is_active = false;
    }
    if let Ok(mut cam) = cameras.get_mut(target) {
        cam.is_active = true;
    }
    // The crop belongs to the frame, so it follows the cut.
    if let Ok(settings) = letterbox.get(current) {
        commands.entity(current).remove::<LetterboxSettings>();
        commands.entity(target).insert(*settings);
    }
    // Damped looks and softened mounts reseed instead of chasing the
    // other camera's rotation.
    baked.last_pose = None;
    baked.held_rot = None;
    cuts.write(SequenceCut {
        from: current,
        to: target,
        shot: baked.compiled.shot_index(playhead),
    });
    state.camera = Some(target);
}

/// Write the evaluated pose onto the cine camera: transform, fov, and
/// the lens components (depth of field, exposure) when the shot asks.
/// During handback, chase the live camera's fresh pose (the game's rig
/// runs and we glide to it).
/// Soften a held camera's mount: chase the mount's world rotation with
/// an exponential decay instead of inheriting every jolt, then hand the
/// result back in the camera's local space, which is what gets written.
/// Position stays welded — a gimbal keeps its mount point, and a
/// first-order position filter would trail the mount at any steady speed.
fn soften_mount(
    baked: &mut Baked,
    pose: &mut CameraPose,
    playhead: f32,
    dt: f32,
    mount: Option<Quat>,
) {
    let (Some(decay), Some(mount)) = (baked.compiled.held_damping_at(playhead), mount) else {
        // Welded, or nothing to be mounted on.
        baked.held_rot = None;
        return;
    };
    let target = mount * pose.rotation;
    let mut smoothed = baked.held_rot.unwrap_or(target);
    if dt > 0.0 {
        smoothed.smooth_nudge(&target, decay, dt);
    } else {
        smoothed = target;
    }
    baked.held_rot = Some(smoothed);
    pose.rotation = mount.inverse() * smoothed;
}

#[allow(clippy::too_many_arguments)] // the frame's one write-out
pub(crate) fn apply_pose(
    mut commands: Commands,
    mut state: ResMut<DirectorState>,
    virtual_time: Res<Time<Virtual>>,
    real_time: Res<Time<Real>>,
    // The pose lands on whichever camera is on air; the playback state
    // driving it stays put on the anchor across cuts. Disjoint
    // components, so the two may name the same entity.
    mut driven: Query<(&mut Transform, &mut Projection, Option<&PreTakeState>), With<CineCamera>>,
    mut playback: Query<(
        Option<(&SequencePlayer, &mut Baked)>,
        Option<&mut HandbackBlend>,
    )>,
    live: Query<(&Transform, Option<&Projection>), Without<CineCamera>>,
    names: Query<(&Name, &GlobalTransform)>,
    parents: Query<&ChildOf>,
    globals: Query<&GlobalTransform>,
    mut cameras: Query<&mut Camera>,
) {
    let Some(camera) = state.camera else {
        return;
    };
    let Some(anchor) = state.take_anchor() else {
        return;
    };
    let (borrowed, pre_take_pose, base_grading) = match driven.get(camera) {
        Ok((_, _, pre_take)) => (
            pre_take.is_some_and(|p| p.role == TakeRole::Borrowed),
            pre_take.map(|p| snapshot_of(&p.transform, Some(&p.projection))),
            pre_take.and_then(|p| p.grading.clone()),
        ),
        Err(_) => return,
    };
    let Ok((playing, handback)) = playback.get_mut(anchor) else {
        return;
    };
    // Name positions are last frame's globals: fine for aim targets.
    let resolve = |wanted: &str| {
        names
            .iter()
            .find(|(name, _)| name.as_str() == wanted)
            .map(|(_, gt)| gt.translation())
    };

    let (pose, lens_flags) = match state.phase {
        DirectorPhase::Shooting => {
            let Some((player, mut baked)) = playing else {
                return;
            };
            let dt = match player.clock {
                ClockSource::Virtual => virtual_time.delta_secs(),
                ClockSource::Real => real_time.delta_secs(),
            };
            let ctx = EvalCtx {
                live: &baked.live,
                dt,
                prev_rot: baked.last_pose.map(|p| p.rotation),
                resolve_entity: &resolve,
                // The on-air camera's parked pose: Held shots ride it.
                held: pre_take_pose,
            };
            let mut pose = baked.compiled.pose_at(player.playhead, &ctx);
            baked.last_pose = Some(pose);
            // The mount's world rotation is last frame's — propagation
            // runs after us — which is a frame of lag inside a filter
            // built to lag.
            let mount = parents
                .get(camera)
                .ok()
                .and_then(|child_of| globals.get(child_of.parent()).ok())
                .map(|global| global.rotation());
            soften_mount(&mut baked, &mut pose, player.playhead, dt, mount);
            let touch = LensTouch::of(&pose);
            // What the shot wants plus what it just dropped: the union
            // is the one frame a removal needs.
            let flags = Some(touch.union(baked.lens_active));
            baked.lens_active = touch;
            (pose, flags)
        }
        DirectorPhase::Handback => {
            let Some(mut handback) = handback else {
                return;
            };
            handback.elapsed += match handback.clock {
                ClockSource::Virtual => virtual_time.delta_secs(),
                ClockSource::Real => real_time.delta_secs(),
            };
            // Borrowing, there is no second camera to chase: glide back
            // to the pose the take took over, which is also what the
            // restore writes, so the last blended frame is the landing.
            let target = if borrowed {
                pre_take_pose
            } else {
                state
                    .live_camera
                    .and_then(|e| live.get(e).ok())
                    .map(|(t, p)| snapshot_of(t, p))
            }
            .unwrap_or(CameraSnapshot {
                position: handback.from.position,
                rotation: handback.from.rotation,
                fov_y: handback.from.fov_y,
            });
            let target = CameraPose::from_snapshot(&target);
            let w = handback
                .blend
                .ease
                .sample_clamped((handback.elapsed / handback.blend.secs).clamp(0.0, 1.0));
            let pose = mix(&handback.from, &target, w);
            if handback.elapsed >= handback.blend.secs {
                restore_live(&mut commands, &mut state, &mut cameras);
            }
            (pose, None)
        }
        _ => return,
    };

    let Ok((mut transform, mut projection, _)) = driven.get_mut(camera) else {
        return;
    };
    transform.translation = pose.position;
    transform.rotation = pose.rotation;
    if let Projection::Perspective(perspective) = &mut *projection {
        perspective.fov = pose.fov_y;
    }

    if let Some(touch) = lens_flags {
        apply_lens_components(&mut commands, camera, &pose, touch, base_grading.as_ref());
    }
}

/// Put the pose's lens components on the camera, taking off the ones it
/// no longer asks for. Only the flagged components are touched, so a
/// shot with no lens work issues no commands at all.
///
/// Grading composes: the shot's offsets ride on top of `base_grading`,
/// the grade the camera had before the take, so a game's own look is
/// still there underneath a graded shot.
pub(crate) fn apply_lens_components(
    commands: &mut Commands,
    camera: Entity,
    pose: &CameraPose,
    touch: LensTouch,
    base_grading: Option<&ColorGrading>,
) {
    if touch.dof {
        match pose.dof {
            Some(d) => {
                commands.entity(camera).insert(DepthOfField {
                    mode: if d.bokeh {
                        DepthOfFieldMode::Bokeh
                    } else {
                        DepthOfFieldMode::Gaussian
                    },
                    focal_distance: d.focal_distance,
                    aperture_f_stops: d.aperture_f_stops,
                    sensor_height: d.sensor_height,
                    ..Default::default()
                });
            }
            None => {
                commands.entity(camera).remove::<DepthOfField>();
            }
        }
    }
    if touch.exposure {
        match pose.exposure_ev100 {
            Some(ev100) => {
                commands.entity(camera).insert(Exposure { ev100 });
            }
            None => {
                commands.entity(camera).remove::<Exposure>();
            }
        }
    }
    if touch.vignette {
        match pose.vignette {
            Some(intensity) => {
                commands.entity(camera).insert(Vignette {
                    intensity,
                    ..Default::default()
                });
            }
            None => {
                commands.entity(camera).remove::<Vignette>();
            }
        }
    }
    if touch.distortion {
        match pose.distortion {
            Some(intensity) => {
                commands.entity(camera).insert(LensDistortion {
                    intensity,
                    ..Default::default()
                });
            }
            None => {
                commands.entity(camera).remove::<LensDistortion>();
            }
        }
    }
    if touch.aberration {
        match pose.aberration {
            Some(intensity) => {
                commands.entity(camera).insert(ChromaticAberration {
                    intensity,
                    ..Default::default()
                });
            }
            None => {
                commands.entity(camera).remove::<ChromaticAberration>();
            }
        }
    }
    if touch.motion_blur {
        match pose.motion_blur {
            Some(spec) => {
                commands.entity(camera).insert(MotionBlur {
                    shutter_angle: spec.shutter_angle,
                    samples: spec.samples,
                });
            }
            // The prepass MotionBlur required stays until the take ends,
            // where the restore knows whose it was.
            None => {
                commands.entity(camera).remove::<MotionBlur>();
            }
        }
    }
    if touch.grading {
        match pose.grading {
            Some(grade) => {
                let mut grading = base_grading.cloned().unwrap_or_default();
                grading.global.exposure += grade.exposure;
                grading.global.temperature += grade.temperature;
                grading.global.tint += grade.tint;
                grading.global.post_saturation *= grade.saturation;
                commands.entity(camera).insert(grading);
            }
            // Mid-take the game's own grade goes back on; a camera that
            // never had one renders with bevy's default either way.
            None => match base_grading {
                Some(saved) => {
                    commands.entity(camera).insert(saved.clone());
                }
                None => {
                    commands.entity(camera).remove::<ColorGrading>();
                }
            },
        }
    }
}

/// Refresh [`ActiveTexts`] from the playing take. Level-triggered off
/// the playhead, so seeks, loops, and reverse playback just work. The
/// viewfinder phase is deliberately left alone: the editor's session
/// writer owns the resource there.
pub(crate) fn update_active_texts(
    state: Res<DirectorState>,
    players: Query<(&SequencePlayer, &Baked)>,
    mut active: ResMut<ActiveTexts>,
) {
    match state.phase {
        DirectorPhase::Shooting => {
            let playing = state
                .take_anchor()
                .and_then(|camera| players.get(camera).ok());
            match playing {
                Some((player, baked)) => {
                    // Don't dirty the resource while it stays empty.
                    if baked.compiled.texts().is_empty() && active.blocks.is_empty() {
                        return;
                    }
                    let blocks = &mut active.blocks;
                    baked.compiled.active_texts_into(player.playhead, blocks);
                }
                None => {
                    if !active.blocks.is_empty() {
                        active.blocks.clear();
                    }
                }
            }
        }
        DirectorPhase::Viewfinder => {}
        _ => {
            if !active.blocks.is_empty() {
                active.blocks.clear();
            }
        }
    }
}

/// Refresh [`ActiveActorCues`] from the playing take: the actor twin of
/// [`update_active_texts`], with the same rules — level-triggered off
/// the playhead, cleared outside Shooting (a skip empties it the same
/// frame the finish routes), and left alone during Viewfinder where the
/// editor's session writer owns it.
pub(crate) fn update_active_actor_cues(
    state: Res<DirectorState>,
    players: Query<(&SequencePlayer, &Baked)>,
    mut active: ResMut<ActiveActorCues>,
) {
    match state.phase {
        DirectorPhase::Shooting => {
            let playing = state
                .take_anchor()
                .and_then(|camera| players.get(camera).ok());
            match playing {
                Some((player, baked)) => {
                    // Don't dirty the resource while it stays empty.
                    if baked.compiled.actors().is_empty() && active.cues.is_empty() {
                        return;
                    }
                    let cues = &mut active.cues;
                    baked.compiled.active_actor_cues_into(player.playhead, cues);
                }
                None => {
                    if !active.cues.is_empty() {
                        active.cues.clear();
                    }
                }
            }
        }
        DirectorPhase::Viewfinder => {}
        _ => {
            if !active.cues.is_empty() {
                active.cues.clear();
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::DirectorPlugin;
    use crate::sequence::*;
    use bevy::app::App;
    use bevy::asset::AssetPlugin;
    use bevy::time::TimeUpdateStrategy;
    use std::time::Duration;

    fn test_sequence(blend_out: Option<Blend>) -> SequenceAsset {
        SequenceAsset {
            name: "test".into(),
            shots: vec![Shot {
                start: 0.0,
                duration: 0.1,
                blend_in: None,
                rig: Rig::Keys {
                    keys: vec![Key {
                        time: 0.0,
                        pos: Vec3::new(5.0, 0.0, 0.0),
                        rot: Some(Quat::IDENTITY),
                        ease: EaseFunction::Linear,
                    }],
                    interp: KeyInterp::Eased,
                },
                look: Look::Free,
                lens: Lens::default(),
                shake: None,
                camera: None,
            }],
            markers: vec![Marker {
                time: 0.05,
                name: "beat".into(),
            }],
            texts: vec![],
            actors: vec![],
            blend_out,
        }
    }

    /// One gameplay camera and nothing else: the director borrows it.
    fn test_app() -> (App, Entity, Handle<SequenceAsset>) {
        let mut app = App::new();
        app.add_plugins((MinimalPlugins, AssetPlugin::default(), DirectorPlugin));
        app.insert_resource(TimeUpdateStrategy::ManualDuration(Duration::from_millis(
            16,
        )));
        let live = app
            .world_mut()
            .spawn((
                Camera3d::default(),
                Camera::default(),
                Projection::default(),
                Transform::from_xyz(0.0, 9.0, 0.0),
            ))
            .id();
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(test_sequence(None));
        (app, live, handle)
    }

    /// A game that brought its own cine camera: the director adopts it
    /// and swaps the frame over.
    fn test_app_dedicated() -> (App, Entity, Entity, Handle<SequenceAsset>) {
        let (mut app, live, handle) = test_app();
        let cine = app
            .world_mut()
            .spawn((
                CineCamera,
                Camera3d::default(),
                Camera {
                    is_active: false,
                    ..Default::default()
                },
                Projection::default(),
                Transform::default(),
            ))
            .id();
        (app, live, cine, handle)
    }

    fn phase(app: &App) -> DirectorPhase {
        app.world().resource::<DirectorState>().phase
    }

    fn is_active(app: &mut App, e: Entity) -> bool {
        app.world().get::<Camera>(e).unwrap().is_active
    }

    #[test]
    fn play_swaps_is_active_and_finishes() {
        let (mut app, live, cine, handle) = test_app_dedicated();
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        assert_eq!(phase(&app), DirectorPhase::Shooting);
        assert!(!is_active(&mut app, live));
        assert_eq!(app.world().resource::<DirectorState>().camera, Some(cine));
        assert!(is_active(&mut app, cine));
        // 0.1 s sequence at 16 ms steps: done well within 20 frames.
        for _ in 0..20 {
            app.update();
        }
        assert_eq!(phase(&app), DirectorPhase::Idle);
        assert!(is_active(&mut app, live));
        assert!(!is_active(&mut app, cine));
        // The pose landed on the cine camera while it was shooting.
        let t = app.world().get::<Transform>(cine).unwrap();
        assert_eq!(t.translation.x, 5.0);
    }

    #[test]
    fn borrow_drives_the_gameplay_camera_and_puts_it_back() {
        let (mut app, live, handle) = test_app();
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        // No second camera: the game's own is the one being directed.
        let state = app.world().resource::<DirectorState>();
        assert!(state.is_borrowing());
        assert_eq!(state.camera, Some(live));
        assert_eq!(
            app.world_mut()
                .query::<&Camera3d>()
                .iter(app.world())
                .count(),
            1
        );
        // It never goes dark, and it is driven where it stands.
        assert!(is_active(&mut app, live));
        assert_eq!(
            app.world().get::<Transform>(live).unwrap().translation.x,
            5.0
        );

        for _ in 0..20 {
            app.update();
        }
        assert_eq!(phase(&app), DirectorPhase::Idle);
        assert!(is_active(&mut app, live));
        // Pose handed back, marker and bookkeeping gone.
        assert_eq!(
            app.world().get::<Transform>(live).unwrap().translation,
            Vec3::new(0.0, 9.0, 0.0)
        );
        assert!(app.world().get::<CineCamera>(live).is_none());
        assert!(app.world().get::<PreTakeState>(live).is_none());
    }

    #[test]
    fn borrowed_handback_lands_on_the_pose_it_took_over() {
        let (mut app, live, _) = test_app();
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(test_sequence(Some(Blend {
                secs: 0.05,
                ease: EaseFunction::Linear,
            })));
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        for _ in 0..40 {
            app.update();
        }
        assert_eq!(phase(&app), DirectorPhase::Idle);
        assert_eq!(
            app.world().get::<Transform>(live).unwrap().translation,
            Vec3::new(0.0, 9.0, 0.0)
        );
    }

    #[test]
    fn borrow_restores_the_viewport_and_lens_the_game_owned() {
        let (mut app, live, handle) = test_app();
        let viewport = bevy::camera::Viewport {
            physical_position: UVec2::new(4, 8),
            physical_size: UVec2::new(320, 240),
            ..Default::default()
        };
        app.world_mut().entity_mut(live).insert((
            Camera {
                viewport: Some(viewport.clone()),
                ..Default::default()
            },
            Exposure { ev100: 7.0 },
        ));
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions {
                letterbox: Some(2.39),
                ..Default::default()
            },
        });
        for _ in 0..20 {
            app.update();
        }
        assert_eq!(phase(&app), DirectorPhase::Idle);
        let camera = app.world().get::<Camera>(live).unwrap();
        assert_eq!(
            camera.viewport.as_ref().map(|v| v.physical_size),
            Some(viewport.physical_size)
        );
        assert_eq!(
            app.world().get::<Exposure>(live).map(|e| e.ev100),
            Some(7.0)
        );
    }

    #[test]
    fn adopted_cine_camera_keeps_its_own_lens() {
        let (mut app, _, cine, handle) = test_app_dedicated();
        app.world_mut()
            .entity_mut(cine)
            .insert(Exposure { ev100: 3.5 });
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        for _ in 0..20 {
            app.update();
        }
        assert_eq!(phase(&app), DirectorPhase::Idle);
        assert_eq!(
            app.world().get::<Exposure>(cine).map(|e| e.ev100),
            Some(3.5)
        );
    }

    #[test]
    fn borrowed_camera_despawning_mid_take_just_goes_idle() {
        let (mut app, live, handle) = test_app();
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        app.world_mut().entity_mut(live).despawn();
        app.update();
        assert_eq!(phase(&app), DirectorPhase::Idle);
        assert_eq!(app.world().resource::<DirectorState>().camera, None);
    }

    #[cfg(feature = "titles")]
    #[test]
    fn director_plugin_installs_the_text_overlay() {
        let (app, ..) = test_app();
        assert!(app.is_plugin_added::<crate::titles::TitlesPlugin>());
    }

    /// A take that uses every filmic track, so the apply and restore
    /// paths are exercised end to end.
    fn filmic_sequence() -> SequenceAsset {
        let mut sequence = test_sequence(None);
        let lens = &mut sequence.shots[0].lens;
        lens.vignette = Some(ScalarTrack::constant(0.6));
        lens.distortion = Some(ScalarTrack::constant(0.15));
        lens.aberration = Some(ScalarTrack::constant(0.04));
        lens.motion_blur = Some(crate::sequence::MotionBlurSpec {
            shutter_angle: 0.5,
            samples: 2,
        });
        sequence
    }

    #[test]
    fn filmic_components_ride_the_take_and_leave_with_it() {
        let (mut app, live, _) = test_app();
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(filmic_sequence());
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        assert_eq!(
            app.world().get::<Vignette>(live).map(|v| v.intensity),
            Some(0.6)
        );
        assert_eq!(
            app.world().get::<LensDistortion>(live).map(|d| d.intensity),
            Some(0.15)
        );
        assert_eq!(
            app.world()
                .get::<ChromaticAberration>(live)
                .map(|a| a.intensity),
            Some(0.04)
        );
        assert_eq!(
            app.world().get::<MotionBlur>(live).map(|m| m.samples),
            Some(2)
        );
        // MotionBlur requires the prepass, so inserting it brought one in.
        assert!(app.world().get::<MotionVectorPrepass>(live).is_some());

        for _ in 0..20 {
            app.update();
        }
        assert_eq!(phase(&app), DirectorPhase::Idle);
        assert!(app.world().get::<Vignette>(live).is_none());
        assert!(app.world().get::<LensDistortion>(live).is_none());
        assert!(app.world().get::<ChromaticAberration>(live).is_none());
        assert!(app.world().get::<MotionBlur>(live).is_none());
        // The prepass was ours, so it goes too.
        assert!(app.world().get::<MotionVectorPrepass>(live).is_none());
    }

    #[test]
    fn motion_blur_leaves_the_games_own_prepass_alone() {
        let (mut app, live, _) = test_app();
        app.world_mut().entity_mut(live).insert(MotionVectorPrepass);
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(filmic_sequence());
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        for _ in 0..20 {
            app.update();
        }
        assert_eq!(phase(&app), DirectorPhase::Idle);
        assert!(app.world().get::<MotionVectorPrepass>(live).is_some());
    }

    #[test]
    fn grading_composes_over_the_games_grade_and_hands_it_back() {
        let (mut app, live, _) = test_app();
        let mut base = ColorGrading::default();
        base.global.exposure = 1.0;
        base.global.post_saturation = 0.8;
        app.world_mut().entity_mut(live).insert(base);
        let mut sequence = test_sequence(None);
        sequence.shots[0].lens.grading = Some(crate::sequence::GradeTrack {
            exposure: Some(ScalarTrack::constant(2.0)),
            saturation: Some(ScalarTrack::constant(0.5)),
            ..Default::default()
        });
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(sequence);
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        let live_grade = app.world().get::<ColorGrading>(live).unwrap();
        // Offsets add, saturation multiplies: the game's look survives.
        assert_eq!(live_grade.global.exposure, 3.0);
        assert!((live_grade.global.post_saturation - 0.4).abs() < 1e-6);

        for _ in 0..20 {
            app.update();
        }
        assert_eq!(phase(&app), DirectorPhase::Idle);
        let restored = app.world().get::<ColorGrading>(live).unwrap();
        assert_eq!(restored.global.exposure, 1.0);
        assert_eq!(restored.global.post_saturation, 0.8);
    }

    /// Two shots: the first on the take's own camera, the second cutting
    /// to a named one.
    fn cut_sequence(name: &str) -> SequenceAsset {
        let mut sequence = test_sequence(None);
        sequence.shots[0].duration = 0.05;
        let mut second = sequence.shots[0].clone();
        second.start = 0.05;
        second.camera = Some(name.to_string());
        if let Rig::Keys { keys, .. } = &mut second.rig {
            keys[0].pos = Vec3::new(-7.0, 0.0, 0.0);
        }
        sequence.shots.push(second);
        sequence.markers.clear();
        sequence
    }

    fn spawn_named_cine(app: &mut App, name: &str) -> Entity {
        app.world_mut()
            .spawn((
                Name::new(name.to_string()),
                CineCamera,
                Camera3d::default(),
                Camera {
                    is_active: false,
                    ..Default::default()
                },
                Projection::default(),
                Transform::from_xyz(0.0, 1.0, 0.0),
            ))
            .id()
    }

    #[test]
    fn a_cut_moves_the_frame_the_letterbox_and_reports_itself() {
        let (mut app, live, _) = test_app();
        let crane = spawn_named_cine(&mut app, "crane");
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(cut_sequence("crane"));
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions {
                letterbox: Some(2.39),
                ..Default::default()
            },
        });
        app.update();
        // Shot one is on the borrowed gameplay camera.
        assert_eq!(app.world().resource::<DirectorState>().camera, Some(live));

        // Run into shot two.
        for _ in 0..4 {
            app.update();
        }
        let state = app.world().resource::<DirectorState>();
        assert_eq!(state.camera, Some(crane));
        // The anchor keeps the playback while the crane takes the frame.
        assert_eq!(state.anchor, Some(live));
        assert!(is_active(&mut app, crane));
        assert!(!is_active(&mut app, live));
        assert!(app.world().get::<LetterboxSettings>(crane).is_some());
        assert!(app.world().get::<LetterboxSettings>(live).is_none());
        assert!(app.world().get::<SequencePlayer>(live).is_some());
        assert_eq!(
            app.world().get::<Transform>(crane).unwrap().translation.x,
            -7.0
        );

        for _ in 0..20 {
            app.update();
        }
        assert_eq!(phase(&app), DirectorPhase::Idle);
        // Both cameras come back: the game's on air, the crane where it
        // was parked, neither carrying take state.
        assert!(is_active(&mut app, live));
        assert!(!is_active(&mut app, crane));
        assert!(app.world().get::<PreTakeState>(live).is_none());
        assert!(app.world().get::<PreTakeState>(crane).is_none());
        assert!(app.world().get::<CineCamera>(live).is_none());
        assert_eq!(
            app.world().get::<Transform>(crane).unwrap().translation,
            Vec3::new(0.0, 1.0, 0.0)
        );
        assert_eq!(
            app.world().get::<Transform>(live).unwrap().translation,
            Vec3::new(0.0, 9.0, 0.0)
        );
    }

    #[test]
    fn a_cut_to_a_camera_nobody_has_stays_on_the_take() {
        let (mut app, live, _) = test_app();
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(cut_sequence("nobody"));
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        for _ in 0..5 {
            app.update();
        }
        assert_eq!(phase(&app), DirectorPhase::Shooting);
        assert_eq!(app.world().resource::<DirectorState>().camera, Some(live));
        assert!(is_active(&mut app, live));
    }

    #[test]
    fn losing_a_cut_target_falls_back_instead_of_ending_the_take() {
        let (mut app, live, _) = test_app();
        let crane = spawn_named_cine(&mut app, "crane");
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(cut_sequence("crane"));
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        for _ in 0..5 {
            app.update();
        }
        assert_eq!(app.world().resource::<DirectorState>().camera, Some(crane));
        app.world_mut().entity_mut(crane).despawn();
        app.update();
        // The anchor still has the playback, so the take survives.
        assert_eq!(phase(&app), DirectorPhase::Shooting);
        assert_eq!(app.world().resource::<DirectorState>().camera, Some(live));
        assert!(is_active(&mut app, live));
    }

    /// A damped mount lags the bike's lean instead of inheriting it, then
    /// settles onto it once the bike holds still. Needs real propagation:
    /// the smoothing reads the mount's GlobalTransform.
    #[test]
    fn a_damped_mount_lags_its_parents_lean_and_settles() {
        let (mut app, _live, _) = test_app();
        app.add_plugins(bevy::transform::TransformPlugin);
        let bike = app.world_mut().spawn(Transform::default()).id();
        let mirror = app
            .world_mut()
            .spawn((
                Name::new("mirror"),
                CineCamera,
                Camera3d::default(),
                Camera {
                    is_active: false,
                    ..Default::default()
                },
                Projection::default(),
                Transform::default(),
                ChildOf(bike),
            ))
            .id();

        let mut sequence = test_sequence(None);
        sequence.shots[0].duration = 0.05;
        let mut held = Shot::held(0.05, 2.0).mount_damping(6.0);
        held.camera = Some("mirror".into());
        sequence.shots.push(held);
        sequence.markers.clear();
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(sequence);
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        // 16 ms a frame: several to reach the held shot and seed it.
        for _ in 0..6 {
            app.update();
        }
        assert_eq!(app.world().resource::<DirectorState>().camera, Some(mirror));

        // Bank the bike hard, then hold it there.
        let lean = Quat::from_rotation_z(0.6);
        app.world_mut().get_mut::<Transform>(bike).unwrap().rotation = lean;
        app.update();
        app.update();
        let local = app.world().get::<Transform>(mirror).unwrap().rotation;
        // Welded would leave the local rotation at identity; a softened
        // mount counter-rotates to hold the frame back.
        assert!(
            local.angle_between(Quat::IDENTITY) > 0.05,
            "the mount never softened: {local:?}"
        );
        assert!(
            (lean * local).angle_between(lean) < 0.6,
            "the camera outran its own mount"
        );

        // Held steady, the smoothing converges and the counter-rotation
        // decays back to nothing.
        for _ in 0..80 {
            app.update();
        }
        let settled = app.world().get::<Transform>(mirror).unwrap().rotation;
        assert!(
            settled.angle_between(Quat::IDENTITY) < 0.02,
            "the mount never settled: {settled:?}"
        );
    }

    #[test]
    fn a_cut_to_a_parented_held_camera_rides_its_mount() {
        let (mut app, _live, _) = test_app();
        let bike = app
            .world_mut()
            .spawn(Transform::from_xyz(0.0, 0.0, 0.0))
            .id();
        let mount = Vec3::new(0.4, 1.0, 0.1);
        let mirror = app
            .world_mut()
            .spawn((
                Name::new("mirror"),
                CineCamera,
                Camera3d::default(),
                Camera {
                    is_active: false,
                    ..Default::default()
                },
                Projection::Perspective(PerspectiveProjection {
                    fov: 1.2,
                    ..Default::default()
                }),
                Transform::from_translation(mount),
                ChildOf(bike),
            ))
            .id();

        let mut sequence = test_sequence(None);
        sequence.shots[0].duration = 0.05;
        let mut second = Shot::held(0.05, 0.2);
        second.camera = Some("mirror".into());
        sequence.shots.push(second);
        sequence.markers.clear();
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(sequence);
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        for _ in 0..5 {
            app.update();
            // The bike rides on regardless of the director.
            app.world_mut()
                .get_mut::<Transform>(bike)
                .unwrap()
                .translation
                .x += 1.0;
        }
        assert_eq!(app.world().resource::<DirectorState>().camera, Some(mirror));
        // The held shot writes the mirror's own parked LOCAL pose back:
        // the mount offset, untouched, while the parent carries it.
        assert_eq!(
            app.world().get::<Transform>(mirror).unwrap().translation,
            mount
        );
        // And the mirror's own fov, not the authored default 45 degrees.
        let Projection::Perspective(p) = app.world().get::<Projection>(mirror).unwrap() else {
            panic!("perspective expected");
        };
        assert_eq!(p.fov, 1.2);

        for _ in 0..20 {
            app.update();
        }
        assert_eq!(phase(&app), DirectorPhase::Idle);
        assert!(app.world().get::<PreTakeState>(mirror).is_none());
        assert_eq!(
            app.world().get::<Transform>(mirror).unwrap().translation,
            mount
        );
    }

    #[test]
    fn a_take_that_ends_cut_away_skips_the_handback() {
        let (mut app, _, _) = test_app();
        spawn_named_cine(&mut app, "crane");
        let mut sequence = cut_sequence("crane");
        sequence.blend_out = Some(Blend {
            secs: 0.2,
            ease: EaseFunction::Linear,
        });
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(sequence);
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        let mut saw_handback = false;
        for _ in 0..40 {
            app.update();
            if phase(&app) == DirectorPhase::Handback {
                saw_handback = true;
            }
        }
        // Gliding a camera the game is not getting back means nothing.
        assert!(!saw_handback);
        assert_eq!(phase(&app), DirectorPhase::Idle);
    }

    #[test]
    fn blend_out_routes_through_handback() {
        let (mut app, live, _) = test_app();
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(test_sequence(Some(Blend {
                secs: 0.05,
                ease: EaseFunction::Linear,
            })));
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        let mut saw_handback = false;
        for _ in 0..40 {
            app.update();
            if phase(&app) == DirectorPhase::Handback {
                saw_handback = true;
            }
        }
        assert!(saw_handback);
        assert_eq!(phase(&app), DirectorPhase::Idle);
        assert!(is_active(&mut app, live));
    }

    #[test]
    fn orphan_guard_restores_live_camera() {
        let (mut app, live, cine, handle) = test_app_dedicated();
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        app.world_mut().entity_mut(cine).despawn();
        app.update();
        assert_eq!(phase(&app), DirectorPhase::Idle);
        assert!(is_active(&mut app, live));
    }

    #[test]
    fn pause_of_virtual_clock_freezes_playhead() {
        let (mut app, _, handle) = test_app();
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        app.world_mut().resource_mut::<Time<Virtual>>().pause();
        for _ in 0..10 {
            app.update();
        }
        assert_eq!(phase(&app), DirectorPhase::Shooting);
        let cine = app.world().resource::<DirectorState>().camera.unwrap();
        let head = app.world().get::<SequencePlayer>(cine).unwrap().playhead;
        // One 16 ms step landed before the pause; nothing after.
        assert!(head <= 0.017, "playhead crept to {head}");
    }

    #[derive(Resource, Default)]
    struct MarkerHits(usize);

    fn count_markers(mut hits: ResMut<MarkerHits>, mut reader: MessageReader<MarkerReached>) {
        hits.0 += reader.read().count();
    }

    #[test]
    fn marker_fires_exactly_once() {
        let (mut app, _, handle) = test_app();
        app.init_resource::<MarkerHits>();
        app.add_systems(Update, count_markers);
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        for _ in 0..30 {
            app.update();
        }
        assert_eq!(app.world().resource::<MarkerHits>().0, 1);
    }

    #[test]
    fn active_texts_fill_while_shooting_and_clear_after() {
        let (mut app, _, _) = test_app();
        let mut sequence = test_sequence(None);
        sequence.texts = vec![TextBlock::at(0.0, 0.1, "caption")];
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(sequence);
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        assert_eq!(phase(&app), DirectorPhase::Shooting);
        let active = app.world().resource::<ActiveTexts>();
        assert_eq!(active.blocks.len(), 1);
        assert_eq!(active.blocks[0].block.text, "caption");
        assert_eq!(active.blocks[0].alpha, 1.0);
        for _ in 0..20 {
            app.update();
        }
        assert_eq!(phase(&app), DirectorPhase::Idle);
        assert!(app.world().resource::<ActiveTexts>().blocks.is_empty());
    }

    #[test]
    fn active_actor_cues_fill_while_shooting_and_clear_after() {
        let (mut app, _, _) = test_app();
        let mut sequence = test_sequence(None);
        sequence.actors =
            vec![ActorTrack::entity("player").cue(ActorCue::at(0.0, 0.1, "cutscene.sleeping"))];
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(sequence);
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        assert_eq!(phase(&app), DirectorPhase::Shooting);
        let active = app.world().resource::<ActiveActorCues>();
        assert_eq!(active.cues.len(), 1);
        assert_eq!(active.cues[0].cue.anim, "cutscene.sleeping");
        assert!(matches!(
            &active.cues[0].target,
            crate::sequence::TargetRef::Entity(name) if name == "player"
        ));
        let first_local = active.cues[0].local_time;
        app.update();
        let advanced = app.world().resource::<ActiveActorCues>().cues[0].local_time;
        assert!(advanced > first_local, "local_time never advanced");
        for _ in 0..20 {
            app.update();
        }
        assert_eq!(phase(&app), DirectorPhase::Idle);
        assert!(app.world().resource::<ActiveActorCues>().cues.is_empty());
    }

    #[test]
    fn skip_clears_actor_cues_immediately() {
        let (mut app, _, _) = test_app();
        let mut sequence = test_sequence(None);
        // Long take: without the skip it would still be mid-cue.
        sequence.shots[0].duration = 10.0;
        sequence.actors = vec![ActorTrack::entity("player").cue(ActorCue::at(0.0, 10.0, "sleep"))];
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(sequence);
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        assert!(!app.world().resource::<ActiveActorCues>().cues.is_empty());
        app.world_mut().write_message(DirectorRequest::Skip);
        app.update();
        assert!(app.world().resource::<ActiveActorCues>().cues.is_empty());
    }

    #[test]
    fn pingpong_bounces_between_the_ends() {
        let (mut app, _, handle) = test_app();
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions {
                loop_mode: LoopMode::PingPong,
                ..Default::default()
            },
        });
        app.update();
        let cine = app.world().resource::<DirectorState>().camera.unwrap();
        let mut flipped = false;
        for _ in 0..40 {
            app.update();
            let player = app.world().get::<SequencePlayer>(cine).unwrap();
            assert!((-0.001..=0.101).contains(&player.playhead));
            flipped |= player.rate < 0.0;
        }
        assert!(flipped, "the rate never reflected");
        assert_eq!(phase(&app), DirectorPhase::Shooting);
    }

    #[test]
    fn backward_markers_fire_on_the_mirror_rule() {
        let (mut app, _, handle) = test_app();
        app.init_resource::<MarkerHits>();
        app.add_systems(Update, count_markers);
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        let cine = app.world().resource::<DirectorState>().camera.unwrap();
        {
            let mut entity = app.world_mut().entity_mut(cine);
            let duration = entity.get::<Baked>().unwrap().compiled.duration();
            entity.get_mut::<Baked>().unwrap().marker_cursor = duration;
            let mut player = entity.get_mut::<SequencePlayer>().unwrap();
            player.playhead = duration;
            player.rate = -1.0;
        }
        for _ in 0..30 {
            app.update();
        }
        assert_eq!(app.world().resource::<MarkerHits>().0, 1);
        assert_eq!(phase(&app), DirectorPhase::Idle);
    }
}