whiteoutlib 0.2.0

Read and write Blizzard game assets from Rust: models (MDX, M2, M3), textures (BLP, DDS, PNG, JPEG, BMP, TGA, TIFF, GIF) and archives (CASC, MPQ).
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
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2026 Fernando Sahmkow

#include "mdx_anim.h"

#include <algorithm>
#include <cmath>
#include <cstring>
#include <deque>
#include <optional>
#include <string>
#include <utility>

#include <whiteout/models/wem/anim/clip.h>

#include "mdx_track_slicer.h"

namespace whiteout {
namespace models {
namespace wem {
namespace mdx_anim {

namespace {

constexpr u32 kNoGlobalSequence = mdx::Track<f32>::kNoGlobalSequence;

/// Whether an extent says anything. A default-constructed one is all zeros, and
/// `Extent::valid()` answers "min <= max", which all zeros satisfies โ€” so the
/// question a caller means by "did the source give me one" is volume, not
/// validity.
bool HasExtent(const Extent& extent) {
    return extent.sphereRadius > 0.0f || extent.maximum.x > extent.minimum.x ||
           extent.maximum.y > extent.minimum.y || extent.maximum.z > extent.minimum.z;
}

/// MDX counts in milliseconds; WEM counts in seconds.
///
/// A division, not a multiply by 1e-3: `1500 * 0.001f` is 1.5000001 and
/// `1500 / 1000.0f` is exactly 1.5, and a key at a round frame should land on a
/// round second.
constexpr f32 kMillisecondsPerSecond = 1000.0f;

constexpr f32 Seconds(f32 milliseconds) {
    return milliseconds / kMillisecondsPerSecond;
}

using mdx_slice::InterpOf;
using mdx_slice::ValueTrait;

/// A colour track with red and blue exchanged, tangents and all.
///
/// Warcraft III stores every keyed colour -- KGAC, KLAC, KLBC and KRCO -- blue
/// first, and the static colour beside it red first; WEM's colour channels are
/// RGB. Blizzard's own StarCraft II conversions name the exchanged key on all
/// 222 keyed geoset colours they carry and the plain static on all 604 static
/// ones. Lights have no such witness (Blizzard dropped 167 of 168), but the day
/// and night suns read only one way: Lordaeron's midnight key (0.80, 0.53, 0.31)
/// is moonlight blue exchanged, and its noon ambient (0.98, 0.84, 0.84) a
/// sky-blue fill rather than pink. No shipped ribbon keys its colour. The native
/// renderer reads all four the same way (`mdx_model_adapter.cpp`). The exchange
/// is its own inverse, so the import and the export call the one function.
mdx::Track<Vector3f> SwapRedBlue(mdx::Track<Vector3f> track) {
    for (Vector3f& value : track.keys_data) {
        std::swap(value.x, value.z);
    }
    return track;
}

/// The `Fresnel` or `UvAnimation` feature on @p ordinal, creating a
/// `UvAnimation` if the material has none.
///
/// Through `InitCommon`, which is the one edit that does not make the native
/// block stale (ยง7.1): this is still the import deriving common from native, and
/// a keyed UV transform is precisely the feature ยง7.2.5 says a keyed source
/// leaves with zero rates for the sub-tracks to drive.
u32 FeatureIdFor(Material& material, FeatureKind kind, u32 ordinal) {
    CommonMaterial& common = material.InitCommon();
    for (const MaterialFeature& feature : common.features) {
        if (feature.kind() == kind && feature.layer == ordinal) {
            return feature.id;
        }
    }
    if (kind != FeatureKind::UvAnimation) {
        return kInvalidIndex;
    }
    MaterialFeature feature;
    feature.id = NextFeatureId(common.features);
    feature.layer = ordinal;
    feature.payload = UvAnimationFeature{};
    common.features.push_back(feature);
    return feature.id;
}

class Builder {
public:
    Builder(const mdx::Model& source, const Context& context, Document& document, u32 modelIndex,
            Diagnostics& out)
        : source_(source), context_(context), document_(document),
          model_(document.models[modelIndex]), modelIndex_(modelIndex), out_(out) {}

    void run() {
        buildSequenceClips();
        addNodeTracks();
        addKindTracks();
        addLayerTracks();
        addGeosetAnimationTracks();
        addEvents();
        reserveEmitterClips();
        commit();
    }

private:
    /// One sequence's window on the global timeline, and the clip it became.
    using Window = mdx_slice::Window;

    void buildSequenceClips() {
        windows_.reserve(source_.sequences.size());
        for (const mdx::Sequence& sequence : source_.sequences) {
            Clip clip;
            clip.name = sequence.name;
            clip.model = modelIndex_;
            clip.duration =
                Seconds(static_cast<f32>(sequence.intervalEnd - sequence.intervalStart));
            clip.looping = !mdx::hasFlag(sequence.flags, mdx::Sequence::Flag::NonLooping);
            clip.native.set("intervalStart", static_cast<i64>(sequence.intervalStart));
            clip.native.set("intervalEnd", static_cast<i64>(sequence.intervalEnd));
            SetClipMoveSpeed(clip, sequence.moveSpeed);
            SetClipRarity(clip, sequence.rarity);
            clip.native.set("syncPoint", static_cast<i64>(sequence.syncPoint));
            // The sequence's own extent, which is the one bound WEM stores
            // rather than recomputes: it is the posed model over this clip, and
            // nothing in the file lets it be derived back.
            clip.bounds.minimum = sequence.extent.minimum;
            clip.bounds.maximum = sequence.extent.maximum;
            clip.bounds.sphereRadius = sequence.extent.boundsRadius;
            clip.containers.push_back(baseContainer());

            Window window;
            window.start = static_cast<f32>(sequence.intervalStart);
            window.end = static_cast<f32>(sequence.intervalEnd);
            window.clip = static_cast<u32>(clips_.size());
            windows_.push_back(window);
            clips_.push_back(std::move(clip));
        }
    }

    static SubTrackContainer baseContainer() {
        SubTrackContainer container;
        container.name = "base";
        container.priority = 0;
        container.concurrent = false; // MDX has one layer, and one layer is opaque.
        return container;
    }

    /// The auto-play clip for @p globalSequenceId, made on first use.
    u32 globalClipFor(u32 globalSequenceId) {
        for (const auto& entry : globalClips_) {
            if (entry.first == globalSequenceId) {
                return entry.second;
            }
        }
        if (globalSequenceId >= source_.globalSequences.size()) {
            return kInvalidIndex;
        }
        Clip clip;
        clip.name = "globalSequence_" + std::to_string(globalSequenceId);
        clip.model = modelIndex_;
        clip.duration = Seconds(static_cast<f32>(source_.globalSequences[globalSequenceId]));
        clip.looping = true;
        // The three-format unification: a global sequence, an `.m2` global
        // sequence and M3's SEQS flag 0x2 are all a loop the model runs itself.
        clip.flags = ClipFlags::AutoPlay | ClipFlags::WorldClocked;
        clip.native.set("globalSequenceId", static_cast<i64>(globalSequenceId));
        // Concurrent, unlike the sequence clips' opaque base: a global
        // sequence plays over whatever animation is active, so its container
        // must abstain on the channels it does not key โ€” opaque, it loses
        // the equal-priority tie to the full-body play and its channels
        // freeze at rest (see m2_anim's twin; StarCraft II ships every
        // AlwaysGlobal container runsConcurrent=1).
        SubTrackContainer container = baseContainer();
        container.concurrent = true;
        clip.containers.push_back(std::move(container));

        const u32 index = static_cast<u32>(clips_.size());
        clips_.push_back(std::move(clip));
        globalClips_.emplace_back(globalSequenceId, index);
        return index;
    }

    /// One track, into every clip that plays part of it.
    template <class T>
    void addTrack(const mdx::Track<T>& track, const TrackTarget& target) {
        if (!track.isUsed || track.timestamps.empty()) {
            return;
        }
        constexpr geom::AttrType kType = ValueTrait<T>::kType;
        const Interpolation interp = InterpOf(track.interpolationType, kType);
        const u32 perKey = ValuesPerKey(interp);
        if (track.keys_data.size() < track.timestamps.size() * perKey) {
            out_.warn(DiagCode::AnimTrackDropped,
                      std::string("a ") + ToString(interp) + " track holds " +
                          std::to_string(track.keys_data.size()) + " values for " +
                          std::to_string(track.timestamps.size()) + " keys",
                      ElementRef(ElementKind::Track, kInvalidIndex));
            return;
        }

        // Reserved rather than committed: a channel nothing drives is noise in a
        // format whose whole animation model is "the table declares, the tracks
        // move". `nextFreeId` is pure, so not committing costs nothing.
        const u32 id = model_.animChannels.nextFreeId();
        bool used = false;

        if (track.globalSequenceId != kNoGlobalSequence) {
            const u32 clip = globalClipFor(track.globalSequenceId);
            if (clip == kInvalidIndex) {
                out_.warn(DiagCode::AnimTrackDropped,
                          "a track names global sequence " +
                              std::to_string(track.globalSequenceId) + ", which the model lacks",
                          ElementRef(ElementKind::Track, kInvalidIndex));
                return;
            }
            clips_[clip].containers[0].subTracks.push_back(mdx_slice::WholeTrack(track, id));
            used = true;
        } else {
            for (const Window& window : windows_) {
                SubTrack sub;
                if (mdx_slice::SliceWindow(track, id, window, sub)) {
                    clips_[window.clip].containers[0].subTracks.push_back(std::move(sub));
                    used = true;
                }
            }
        }

        if (!used) {
            return;
        }
        AnimChannel channel;
        channel.id = id;
        channel.target = target;
        channel.valueType = kType;
        model_.animChannels.add(channel);
    }

    u32 nodeOf(u32 objectId) const {
        if (context_.byObjectId == nullptr) {
            return kInvalidNode;
        }
        const auto found = context_.byObjectId->find(objectId);
        return found == context_.byObjectId->end() ? kInvalidNode : found->second;
    }

    static TrackTarget nodeTarget(u32 node, Channel channel, u32 sub = 0) {
        TrackTarget target;
        target.kind = TrackTarget::Kind::Node;
        target.node = node;
        target.channel = channel;
        target.sub = sub;
        return target;
    }

    /// The TRS every node kind carries.
    void addNodeTracks() {
        const auto visit = [this](const mdx::Node& node) {
            const u32 index = nodeOf(node.objectId);
            if (index == kInvalidNode) {
                return;
            }
            addTrack(node.translationTracks, nodeTarget(index, Channel::Translation));
            addTrack(node.rotationTracks, nodeTarget(index, Channel::Rotation));
            addTrack(node.scalingTracks, nodeTarget(index, Channel::Scale));
        };
        for (const mdx::Bone& item : source_.bones) {
            visit(item.node);
        }
        for (const mdx::Helper& item : source_.helpers) {
            visit(item.node);
        }
        for (const mdx::Light& item : source_.lights) {
            visit(item.node);
        }
        for (const mdx::Attachment& item : source_.attachments) {
            visit(item.node);
        }
        for (const mdx::ParticleEmitter& item : source_.particleEmitters) {
            visit(item.node);
        }
        for (const mdx::ParticleEmitter2& item : source_.particleEmitters2) {
            visit(item.node);
        }
        for (const mdx::CornEmitter& item : source_.cornEmitters) {
            visit(item.node);
        }
        for (const mdx::RibbonEmitter& item : source_.ribbonEmitters) {
            visit(item.node);
        }
        for (const mdx::EventObject& item : source_.eventObjects) {
            visit(item.node);
        }
        for (const mdx::CollisionShape& item : source_.collisionShapes) {
            visit(item.node);
        }
    }

    /// What each node kind animates beyond its transform.
    ///
    /// The emitters contribute **visibility only**: ยง18 keeps particle and
    /// ribbon systems out of WEM, so animating an emission rate would be storing
    /// the motion of something the document does not contain.
    void addKindTracks() {
        for (const mdx::Light& light : source_.lights) {
            const u32 node = nodeOf(light.node.objectId);
            if (node == kInvalidNode) {
                continue;
            }
            addTrack(SwapRedBlue(light.colorTracks), nodeTarget(node, Channel::Color));
            addTrack(light.intensityTracks, nodeTarget(node, Channel::Intensity));
            addTrack(light.attenuationStartTracks, nodeTarget(node, Channel::AttenuationStart));
            addTrack(light.attenuationEndTracks, nodeTarget(node, Channel::AttenuationEnd));
            addTrack(light.visibilityTracks, nodeTarget(node, Channel::Visibility));
            // A WC3 light carries a second colour and intensity for its ambient
            // term. Same channel, `sub` 1 โ€” which is what `sub` is for on a node.
            addTrack(SwapRedBlue(light.ambientColorTracks), nodeTarget(node, Channel::Color, 1));
            addTrack(light.ambientIntensityTracks, nodeTarget(node, Channel::Intensity, 1));
        }
        for (const mdx::Attachment& attachment : source_.attachments) {
            const u32 node = nodeOf(attachment.node.objectId);
            if (node != kInvalidNode) {
                addTrack(attachment.visibilityTracks, nodeTarget(node, Channel::Visibility));
            }
        }
        for (const mdx::ParticleEmitter& emitter : source_.particleEmitters) {
            const u32 node = nodeOf(emitter.node.objectId);
            if (node != kInvalidNode) {
                addTrack(emitter.visibilityTracks, nodeTarget(node, Channel::Visibility));
            }
        }
        for (const mdx::ParticleEmitter2& emitter : source_.particleEmitters2) {
            const u32 node = nodeOf(emitter.node.objectId);
            if (node != kInvalidNode) {
                addTrack(emitter.visibilityTracks, nodeTarget(node, Channel::Visibility));
            }
        }
        for (const mdx::RibbonEmitter& ribbon : source_.ribbonEmitters) {
            const u32 node = nodeOf(ribbon.node.objectId);
            if (node == kInvalidNode) {
                continue;
            }
            addTrack(SwapRedBlue(ribbon.colorTracks), nodeTarget(node, Channel::Color));
            addTrack(ribbon.alphaTracks, nodeTarget(node, Channel::Alpha));
            addTrack(ribbon.textureSlotTracks, nodeTarget(node, Channel::TextureIndex));
            addTrack(ribbon.visibilityTracks, nodeTarget(node, Channel::Visibility));
        }
        for (std::size_t c = 0; c < source_.cameras.size(); ++c) {
            if (c >= context_.cameraNodes.size() || context_.cameraNodes[c] == kInvalidNode) {
                continue;
            }
            addTrack(source_.cameras[c].positionTracks,
                     nodeTarget(context_.cameraNodes[c], Channel::Translation));
        }
    }

    /// Per-layer material tracks, once per profile the layer belongs to.
    void addLayerTracks() {
        for (const Context::ProfileLayers& profileLayers : context_.layerOrdinals) {
            ProfileMaterialSet* set = model_.setFor(profileLayers.profile);
            if (set == nullptr) {
                continue;
            }
            for (std::size_t m = 0; m < source_.materials.size(); ++m) {
                if (m >= profileLayers.byMaterial.size() || m >= set->slotBindings.size()) {
                    continue;
                }
                const u32 material = set->slotBindings[m].byLook.empty()
                                         ? kInvalidIndex
                                         : set->slotBindings[m].byLook[0];
                if (material >= set->materials.size()) {
                    continue;
                }
                addOneMaterial(source_.materials[m], profileLayers.byMaterial[m],
                               profileLayers.profile, static_cast<u32>(m),
                               set->materials[material]);
            }
        }
    }

    void addOneMaterial(const mdx::Material& source, const std::vector<u32>& ordinals,
                        ProfileId profile, u32 slot, Material& material) {
        for (std::size_t l = 0; l < source.layers.size() && l < ordinals.size(); ++l) {
            const u32 ordinal = ordinals[l];
            if (ordinal == kInvalidIndex) {
                continue;
            }
            const mdx::Layer& layer = source.layers[l];

            TrackTarget target;
            target.kind = TrackTarget::Kind::MaterialLayer;
            target.material.profile = profile;
            target.material.slot = slot;
            target.material.look = 0;
            target.sub = ordinal;

            target.channel = Channel::Alpha;
            addTrack(layer.alphaTracks, target);
            target.channel = Channel::TextureIndex;
            addTrack(layer.textureIdTracks, target);
            target.channel = Channel::Emissive;
            addTrack(layer.emissiveGainTracks, target);

            addFresnelTracks(layer, profile, slot, ordinal, material);
            addUvTracks(layer, profile, slot, ordinal, material);
        }
    }

    void addFresnelTracks(const mdx::Layer& layer, ProfileId profile, u32 slot, u32 ordinal,
                          Material& material) {
        const bool keyed = layer.fresnelColorTracks.isUsed || layer.fresnelAlphaTracks.isUsed ||
                           layer.fresnelTeamColorTracks.isUsed;
        if (!keyed) {
            return;
        }
        const u32 feature = FeatureIdFor(material, FeatureKind::Fresnel, ordinal);
        if (feature == kInvalidIndex) {
            // The material import only creates a fresnel feature where the static
            // strength is non-zero, so a file that keys one from zero has nothing
            // to hang the track on. Reported rather than invented.
            out_.warn(DiagCode::AnimTrackDropped,
                      "a fresnel track has no feature on layer " + std::to_string(ordinal),
                      ElementRef(ElementKind::Slot, slot), profile);
            return;
        }
        TrackTarget target;
        target.kind = TrackTarget::Kind::MaterialFeature;
        target.material.profile = profile;
        target.material.slot = slot;
        target.material.look = 0;
        target.sub = feature;

        target.channel = Channel::Color;
        addTrack(layer.fresnelColorTracks, target);
        target.channel = Channel::Alpha;
        addTrack(layer.fresnelAlphaTracks, target);
        target.channel = Channel::Weight;
        addTrack(layer.fresnelTeamColorTracks, target);
    }

    void addUvTracks(const mdx::Layer& layer, ProfileId profile, u32 slot, u32 ordinal,
                     Material& material) {
        if (layer.textureAnimationId >= source_.textureAnimations.size()) {
            return; // Including MDX's own -1 for "none".
        }
        const mdx::TextureAnimation& animation =
            source_.textureAnimations[layer.textureAnimationId];
        if (!animation.translationTracks.isUsed && !animation.rotationTracks.isUsed &&
            !animation.scalingTracks.isUsed) {
            return;
        }
        const u32 feature = FeatureIdFor(material, FeatureKind::UvAnimation, ordinal);

        TrackTarget target;
        target.kind = TrackTarget::Kind::MaterialFeature;
        target.material.profile = profile;
        target.material.slot = slot;
        target.material.look = 0;
        target.sub = feature;

        target.channel = Channel::UvTranslate;
        addTrack(animation.translationTracks, target);
        target.channel = Channel::UvRotate;
        addTrack(animation.rotationTracks, target);
        target.channel = Channel::UvScale;
        addTrack(animation.scalingTracks, target);
    }

    /// `GeosetAnimation` keys a **geoset**, which is a section (ยง5.5). This
    /// converter makes one mesh per geoset, so the mesh index is the geoset id
    /// and the section is its only one.
    void addGeosetAnimationTracks() {
        for (const mdx::GeosetAnimation& animation : source_.geosetAnimations) {
            if (animation.geosetId >= model_.meshes.size() ||
                model_.meshes[animation.geosetId].sections.empty()) {
                out_.warn(DiagCode::AnimTrackDropped,
                          "a geoset animation names geoset " + std::to_string(animation.geosetId) +
                              ", which the model does not have",
                          ElementRef(ElementKind::Mesh, animation.geosetId));
                continue;
            }
            TrackTarget target;
            target.kind = TrackTarget::Kind::Section;
            target.mesh = animation.geosetId;
            target.sub = 0;

            target.channel = Channel::Alpha;
            addTrack(animation.alphaTracks, target);
            target.channel = Channel::Color;
            addTrack(SwapRedBlue(animation.colorTracks), target);
        }
    }

    /// An `EventObject`'s KEVT times, sorted into the clip whose window holds
    /// each one. The node is the where, the key is the when (ยง10.8).
    void addEvents() {
        for (const mdx::EventObject& event : source_.eventObjects) {
            const u32 node = nodeOf(event.node.objectId);
            if (node == kInvalidNode) {
                continue;
            }
            if (event.globalSequenceId != kNoGlobalSequence) {
                const u32 clip = globalClipFor(event.globalSequenceId);
                if (clip == kInvalidIndex) {
                    continue;
                }
                for (u32 time : event.eventTrackTimes) {
                    clips_[clip].events.push_back(
                        ClipEvent{Seconds(static_cast<f32>(time)), node, event.node.name, 0});
                }
                continue;
            }
            for (u32 time : event.eventTrackTimes) {
                for (const Window& window : windows_) {
                    if (static_cast<f32>(time) < window.start ||
                        static_cast<f32>(time) > window.end) {
                        continue;
                    }
                    clips_[window.clip].events.push_back(ClipEvent{
                        Seconds(static_cast<f32>(time) - window.start), node, event.node.name, 0});
                }
            }
        }
    }

    /// The clips an emitter's PROPERTY tracks play under.
    ///
    /// WEM does not hold those tracks (ยง18), but a global sequence only they
    /// key is still a loop the model runs: without its auto-play clip a
    /// conversion that crosses the emitter natively (`cross/mdx_m3_effects`)
    /// has no sequence to put its emission rate in. Last, so every clip the
    /// tracks above made keeps its place.
    void reserveEmitterClips() {
        const auto reserve = [this](const auto& track) {
            if (track.isUsed && !track.timestamps.empty() &&
                track.globalSequenceId != kNoGlobalSequence &&
                track.globalSequenceId < source_.globalSequences.size()) {
                globalClipFor(track.globalSequenceId);
            }
        };
        for (const mdx::ParticleEmitter& emitter : source_.particleEmitters) {
            reserve(emitter.emissionRateTracks);
            reserve(emitter.gravityTracks);
            reserve(emitter.longitudeTracks);
            reserve(emitter.latitudeTracks);
            reserve(emitter.lifespanTracks);
            reserve(emitter.speedTracks);
        }
        for (const mdx::ParticleEmitter2& emitter : source_.particleEmitters2) {
            reserve(emitter.speedTracks);
            reserve(emitter.variationTracks);
            reserve(emitter.latitudeTracks);
            reserve(emitter.gravityTracks);
            reserve(emitter.emissionRateTracks);
            reserve(emitter.lengthTracks);
            reserve(emitter.widthTracks);
        }
        for (const mdx::RibbonEmitter& ribbon : source_.ribbonEmitters) {
            reserve(ribbon.heightAboveTracks);
            reserve(ribbon.heightBelowTracks);
        }
    }

    void commit() {
        for (Clip& clip : clips_) {
            document_.clips.push_back(std::move(clip));
        }
    }

    const mdx::Model& source_;
    const Context& context_;
    Document& document_;
    Model& model_;
    u32 modelIndex_;
    Diagnostics& out_;

    std::vector<Clip> clips_;
    std::vector<Window> windows_;
    std::vector<std::pair<u32, u32>> globalClips_;
};

} // namespace

void Import(const mdx::Model& source, const Context& context, Document& document, u32 model,
            Diagnostics& out) {
    if (model >= document.models.size()) {
        return;
    }
    Builder(source, context, document, model, out).run();
}

// ============================================================================
// Export โ€” clips back onto MDX's one global timeline (ยง10.8.3)
//
// The inverse of everything above, and the asymmetry is the whole of it. Import
// sliced one timeline into a clip per sequence and kept the bracketing keys;
// export merges those clips back, and a key two clips share โ€” which is what a
// bracket key IS โ€” has to be written once. So the merge is keyed on the
// ABSOLUTE time, and the first clip to claim a timestamp keeps it.
//
// What cannot round-trip, said once: a clip that carries no `intervalStart` did
// not come from an `.mdx`, and MDX has nowhere to put it but a fresh window at
// the end of the timeline. That is a real re-timing and it is reported.
// ============================================================================

namespace {

constexpr f32 kMilliseconds = 1000.0f;

u32 Milliseconds(f32 seconds) {
    const f32 ms = seconds * kMilliseconds;
    return ms <= 0.0f ? 0u : static_cast<u32>(ms + 0.5f);
}

mdx::InterpolationType MdxInterp(Interpolation interp) {
    switch (interp) {
    case Interpolation::Step:
        return mdx::InterpolationType::None;
    case Interpolation::Hermite:
        return mdx::InterpolationType::Hermite;
    case Interpolation::Bezier:
        return mdx::InterpolationType::Bezier;
    case Interpolation::Linear:
    case Interpolation::Slerp:
    case Interpolation::Count:
        break;
    }
    // A quaternion's Linear IS a shortest-arc slerp in the engine, which is why
    // the import collapsed the two โ€” this is that statement read backwards.
    return mdx::InterpolationType::Linear;
}

/// One channel's keys, gathered off every clip that drives it and rebased onto
/// the global timeline.
struct MergedTrack {
    bool used = false;
    Interpolation interp = Interpolation::Linear;
    u32 globalSequenceId = mdx::Track<f32>::kNoGlobalSequence;
    std::vector<u32> times;      ///< Absolute milliseconds, ascending, unique.
    std::vector<const u8*> keys; ///< One pointer per key, into the sub-track's bytes.
    u32 valuesPerKey = 1;
    std::size_t valueSize = 0;

    /// Claim @p time for @p key. The FIRST claim wins, which is the whole of the
    /// bracket-key rule: the two clips either side of a boundary both carry the
    /// key that sits on it, and it belongs on the timeline once.
    void add(u32 time, const u8* key) {
        pending.emplace_back(time, key);
    }

    /// Ascending by time, one key per time. Stable, so "first claim wins" means
    /// the clip that appeared first in the document.
    void finish() {
        std::stable_sort(pending.begin(), pending.end(),
                         [](const auto& a, const auto& b) { return a.first < b.first; });
        times.clear();
        keys.clear();
        for (const auto& [time, key] : pending) {
            if (!times.empty() && times.back() == time) {
                continue;
            }
            times.push_back(time);
            keys.push_back(key);
        }
        used = !times.empty();
    }

    /// A key the export made up rather than found -- a window edge -- sized
    /// for `valuesPerKey`, its tangents zero. Stable addresses, so `keys` may
    /// point into it.
    const u8* own(std::vector<u8> value) {
        value.resize(valuesPerKey * valueSize, 0);
        synthesized.push_back(std::move(value));
        return synthesized.back().data();
    }

    std::vector<std::pair<u32, const u8*>> pending;
    std::deque<std::vector<u8>> synthesized;
};

/// @p track's value at @p time (seconds) the way its source plays it: the
/// first key held before it and the last past it, stepped or lerped between
/// (a quaternion the short way round, a tangent stream on its values alone).
std::vector<u8> SampleValue(const SubTrack& track, geom::AttrType type, f32 time) {
    const std::size_t size = geom::AttrTypeSize(type);
    const std::size_t stride = ValuesPerKey(track.interp) * size;
    const auto at = [&](std::size_t key) { return track.values.data() + key * stride; };

    std::size_t after = 0;
    while (after < track.times.size() && track.times[after] <= time) {
        ++after;
    }
    if (after == 0) {
        return std::vector<u8>(at(0), at(0) + size);
    }
    const std::size_t before = after - 1;
    if (after >= track.times.size() || track.interp == Interpolation::Step) {
        return std::vector<u8>(at(before), at(before) + size);
    }
    const f32 span = track.times[after] - track.times[before];
    const f32 alpha = span > 0.0f ? (time - track.times[before]) / span : 0.0f;
    std::vector<u8> out(at(before), at(before) + size);
    switch (type) {
    case geom::AttrType::F32:
    case geom::AttrType::F32x2:
    case geom::AttrType::F32x3:
    case geom::AttrType::F32x4: {
        for (std::size_t i = 0; i < size / sizeof(f32); ++i) {
            f32 a = 0, b = 0;
            std::memcpy(&a, at(before) + i * sizeof(f32), sizeof(f32));
            std::memcpy(&b, at(after) + i * sizeof(f32), sizeof(f32));
            const f32 v = a + (b - a) * alpha;
            std::memcpy(out.data() + i * sizeof(f32), &v, sizeof(f32));
        }
        break;
    }
    case geom::AttrType::Quat: {
        f32 a[4], b[4], v[4];
        std::memcpy(a, at(before), sizeof(a));
        std::memcpy(b, at(after), sizeof(b));
        const f32 sign = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3] < 0.0f ? -1.0f : 1.0f;
        f32 length = 0.0f;
        for (int i = 0; i < 4; ++i) {
            v[i] = a[i] + (sign * b[i] - a[i]) * alpha;
            length += v[i] * v[i];
        }
        length = std::sqrt(length);
        for (int i = 0; i < 4; ++i) {
            v[i] = length > 0.0f ? v[i] / length : v[i];
        }
        std::memcpy(out.data(), v, sizeof(v));
        break;
    }
    default:
        break;
    }
    return out;
}

/// Whether @p channel says its UV state the way an `.m3` layer does rather than
/// the way a `TextureAnimation` does: a two-float offset, a three-float euler
/// angle, a two-float tiling against MDX's Vector3 / quaternion / Vector3.
bool IsM3UvSpelling(const AnimChannel& channel) {
    if (channel.target.channel == Channel::UvRotate) {
        return channel.valueType != geom::AttrType::Quat;
    }
    return channel.valueType != geom::AttrType::F32x3;
}

/// One such channel restated in MDX's spelling.
///
/// Both engines turn and scale a layer's UV about the texture centre and both
/// apply the translation in source space ahead of that, but StarCraft II
/// SUBTRACTS its offset where Warcraft III adds it (`M3ComposeUvTransform`
/// against Reforged's `AnimateTextureMap`), so the translation is the offset
/// negated -- exactly, whatever the turn and the tiling. The rotation is
/// `uvAngle.z` about z, the only euler angle a 2x4 UV matrix keeps, and the
/// third component of either vector pair is the one MDX ignores.
///
/// Without this the merged bytes reached `Emit` unread and were decoded as
/// whatever the destination track holds: a two-float offset as a `Vector3f`
/// and a three-float angle as a `Quaternion`, both four bytes past the end of
/// the key. A Heroes crystal exported a texture rotation of
/// (0, 6.28, 0, -7.9e11) -- degenerate, and unnormalisable -- and every
/// crossed scroll left its last key with a junk z.
MergedTrack MdxUvTrack(const MergedTrack& source, const AnimChannel& channel) {
    MergedTrack out;
    out.used = source.used;
    // No `.m3` stream carries tangents, so a converted track is never smooth;
    // a source that says otherwise loses them rather than pairing a quaternion
    // with an euler tangent.
    out.interp = ValuesPerKey(source.interp) > 1 ? Interpolation::Linear : source.interp;
    out.globalSequenceId = source.globalSequenceId;
    out.times = source.times;
    out.valuesPerKey = 1;
    out.valueSize = channel.target.channel == Channel::UvRotate ? sizeof(Quaternion)
                                                                : sizeof(Vector3f);
    const std::size_t comps =
        std::min<std::size_t>(geom::AttrTypeSize(channel.valueType) / sizeof(f32), 4);
    for (const u8* key : source.keys) {
        f32 in[4] = {0.0f, 0.0f, 0.0f, 0.0f};
        std::memcpy(in, key, comps * sizeof(f32));
        f32 written[4] = {0.0f, 0.0f, 0.0f, 0.0f};
        switch (channel.target.channel) {
        case Channel::UvTranslate:
            written[0] = -in[0];
            written[1] = -in[1];
            break;
        case Channel::UvRotate: {
            const f32 half = in[2] * 0.5f;
            written[2] = std::sin(half);
            written[3] = std::cos(half);
            break;
        }
        default:
            written[0] = in[0];
            written[1] = in[1];
            written[2] = 1.0f;
            break;
        }
        std::vector<u8> value(out.valueSize, 0);
        std::memcpy(value.data(), written, out.valueSize);
        out.keys.push_back(out.own(std::move(value)));
    }
    return out;
}

/// Writes a merged track into `dst`, decoding `T` out of the raw value bytes.
template <class T>
void Emit(const MergedTrack& merged, mdx::Track<T>& dst) {
    if (!merged.used || merged.times.empty()) {
        return;
    }
    dst.isUsed = true;
    dst.interpolationType = MdxInterp(merged.interp);
    dst.globalSequenceId = merged.globalSequenceId;
    dst.timestamps = merged.times;
    dst.keyCount = merged.times.size();
    dst.keys_data.clear();
    dst.keys_data.reserve(merged.times.size() * merged.valuesPerKey);
    for (const u8* key : merged.keys) {
        for (u32 v = 0; v < merged.valuesPerKey; ++v) {
            T value{};
            std::memcpy(&value, key + v * sizeof(T), sizeof(T));
            dst.keys_data.push_back(value);
        }
    }
}

class Exporter {
public:
    Exporter(const Document& document, u32 modelIndex, ProfileId profile,
             const ExportContext& context, mdx::Model& out, Diagnostics& diagnostics)
        : document_(document), model_(document.models[modelIndex]), modelIndex_(modelIndex),
          profile_(profile), context_(context), out_(out), diagnostics_(diagnostics) {}

    void run() {
        buildWindows();
        buildVisibilityGates();
        for (const AnimChannel& channel : model_.animChannels.channels) {
            emitChannel(channel);
        }
        emitStandingVisibilityGates();
        emitStandingUvTransforms();
        emitEvents();
    }

private:
    /// Where one clip sits on the global timeline, or which global sequence it
    /// IS. Exactly one of the two.
    struct Window {
        u32 clip = kInvalidIndex;
        u32 start = 0; ///< Milliseconds. Meaningless for a global-sequence clip.
        u32 end = 0;   ///< Milliseconds, inclusive. Same.
        u32 globalSequenceId = mdx::Track<f32>::kNoGlobalSequence;
    };

    static bool IsGlobalClip(const Clip& clip) {
        // The three-format unification, read backwards: an auto-play clip on a
        // clock that is not the host play's is what a global sequence is.
        return hasFlag(clip.flags, ClipFlags::AutoPlay) &&
               hasFlag(clip.flags, ClipFlags::WorldClocked);
    }

    void buildWindows() {
        u32 nextFree = 0;
        for (std::size_t c = 0; c < document_.clips.size(); ++c) {
            const Clip& clip = document_.clips[c];
            if (clip.model != modelIndex_) {
                continue;
            }
            Window window;
            window.clip = static_cast<u32>(c);

            if (IsGlobalClip(clip)) {
                const i64 stored = clip.native.value("globalSequenceId", -1);
                const u32 id = stored >= 0 ? static_cast<u32>(stored)
                                           : static_cast<u32>(out_.globalSequences.size());
                if (out_.globalSequences.size() <= id) {
                    out_.globalSequences.resize(id + 1, 0);
                }
                out_.globalSequences[id] = Milliseconds(clip.duration);
                window.globalSequenceId = id;
                windows_.push_back(window);
                continue;
            }

            mdx::Sequence sequence;
            sequence.name = clip.name;
            const i64 start = clip.native.value("intervalStart", -1);
            const i64 end = clip.native.value("intervalEnd", -1);
            if (start >= 0 && end >= start) {
                sequence.intervalStart = static_cast<u32>(start);
                sequence.intervalEnd = static_cast<u32>(end);
            } else {
                // No window on the clip: it did not come from an `.mdx`. The
                // timeline is the only clock MDX has, so one is allocated after
                // everything already placed โ€” a real re-timing, reported.
                sequence.intervalStart = nextFree;
                sequence.intervalEnd = nextFree + Milliseconds(clip.duration);
                diagnostics_.info(DiagCode::AnimClipRetimed,
                                  "clip '" + clip.name + "' had no MDX interval; placed at " +
                                      std::to_string(sequence.intervalStart) + "ms",
                                  ElementRef(ElementKind::Clip, static_cast<u32>(c)), profile_);
            }
            if (!clip.looping) {
                sequence.flags = mdx::Sequence::Flag::NonLooping;
            }
            sequence.moveSpeed = ClipMoveSpeed(clip);
            sequence.rarity = ClipRarity(clip);
            sequence.syncPoint = static_cast<u32>(clip.native.value("syncPoint", 0));
            // The clip's own extent when it has one, and the model's when it
            // does not โ€” a clip from another format, or one an editor made.
            // Conservative either way, which is the direction a bound may err.
            const Extent& extent = HasExtent(clip.bounds) ? clip.bounds : model_.bounds;
            sequence.extent.minimum = extent.minimum;
            sequence.extent.maximum = extent.maximum;
            sequence.extent.boundsRadius = extent.sphereRadius;

            nextFree = std::max(nextFree, sequence.intervalEnd + 1000u);
            window.start = sequence.intervalStart;
            window.end = sequence.intervalEnd;
            windows_.push_back(window);
            out_.sequences.push_back(std::move(sequence));
        }
    }

    /// Every sub-track driving `channel`, merged onto the timeline.
    MergedTrack gather(const AnimChannel& channel) const {
        MergedTrack merged;
        merged.valueSize = geom::AttrTypeSize(channel.valueType);

        struct Part {
            const Window* window;
            const Clip* clip;
            const SubTrack* track;
        };
        std::vector<Part> parts;
        for (const Window& window : windows_) {
            const Clip& clip = document_.clips[window.clip];
            for (const SubTrackContainer& container : clip.containers) {
                const SubTrack* track = container.find(channel.id);
                if (track == nullptr || track->times.empty()) {
                    continue;
                }
                if (!track->wellSized(channel.valueType)) {
                    diagnostics_.warn(DiagCode::AnimTrackDropped,
                                      "a sub-track of clip '" + clip.name +
                                          "' is not sized for its channel",
                                      ElementRef(ElementKind::Track, channel.id), profile_);
                    continue;
                }
                parts.push_back(Part{&window, &clip, track});
            }
        }
        if (parts.empty()) {
            return merged;
        }

        // One MDX track has one interpolation type, so clips that disagree
        // cannot all be written. The first clip that MOVES between its keys
        // names it: a step written over a ramp turns every key into a jolt,
        // where a ramp written over a step only softens a hold -- and "the
        // first clip wins" held most of the Thor through every sequence it
        // moved in, because a bone at rest in `Stand` stepped there. A
        // tangent stream survives only when every clip carries one. The rest
        // are named.
        merged.interp = parts.front().track->interp;
        for (const Part& part : parts) {
            if (part.track->interp != Interpolation::Step) {
                merged.interp = part.track->interp;
                break;
            }
        }
        for (const Part& part : parts) {
            if (ValuesPerKey(part.track->interp) < ValuesPerKey(merged.interp)) {
                merged.interp = Interpolation::Linear;
                break;
            }
        }
        merged.valuesPerKey = ValuesPerKey(merged.interp);
        merged.globalSequenceId = parts.front().window->globalSequenceId;
        for (const Part& part : parts) {
            if (MdxInterp(part.track->interp) != MdxInterp(merged.interp)) {
                diagnostics_.warn(DiagCode::AnimTrackApproximated,
                                  "clip '" + part.clip->name +
                                      "' interpolates a shared channel as " +
                                      ToString(part.track->interp) + "; written as " +
                                      ToString(merged.interp),
                                  ElementRef(ElementKind::Track, channel.id), profile_);
            }
        }

        for (const Part& part : parts) {
            const Window& window = *part.window;
            const Clip& clip = *part.clip;
            const SubTrack& track = *part.track;
            const u32 stride = ValuesPerKey(track.interp) * static_cast<u32>(merged.valueSize);
            const bool global = window.globalSequenceId != kNoGlobalSequence;
            const u32 start = global ? 0u : window.start;
            const u32 end = global ? Milliseconds(clip.duration) : window.end;
            const auto at = [&](std::size_t k) { return track.values.data() + k * stride; };

            if (clip.native.value("intervalStart", -1) >= 0 ||
                clip.native.value("globalSequenceId", -1) >= 0) {
                // An `.mdx` clip's keys already say what its engine plays,
                // bracket keys included: a bracket key's time is negative or
                // past the clip, which is exactly what puts it back where the
                // neighbouring window's key already is.
                for (std::size_t k = 0; k < track.times.size(); ++k) {
                    const f32 absolute =
                        track.times[k] * kMillisecondsPerSecond + static_cast<f32>(start);
                    merged.add(absolute <= 0.0f ? 0u : static_cast<u32>(absolute + 0.5f), at(k));
                }
                continue;
            }

            // Any other source holds outside its keys and plays nothing past
            // its clip. Warcraft III reads every key inside a window as that
            // window's and has no default before the first or after the last,
            // so it gets the keys inside the window plus the value the source
            // shows at each edge the track does not key -- the start and end
            // key every Warcraft III track has to have. A key past the clip
            // is dropped: on the one timeline it lands in the next window and
            // plays there (the Thor's `Attack` keys ran six seconds past its
            // 3.7 s clip, through `Morph`).
            bool keyedStart = false;
            bool keyedEnd = false;
            for (std::size_t k = 0; k < track.times.size(); ++k) {
                const f32 t = track.times[k];
                if (t < -1e-4f || t > clip.duration + 1e-4f) {
                    continue;
                }
                const u32 time = std::clamp(
                    start + static_cast<u32>(std::max(t, 0.0f) * kMillisecondsPerSecond + 0.5f),
                    start, end);
                keyedStart = keyedStart || time == start;
                keyedEnd = keyedEnd || time == end;
                merged.add(time, at(k));
            }
            if (!keyedStart) {
                merged.add(start, merged.own(SampleValue(track, channel.valueType, 0.0f)));
            }
            if (!keyedEnd) {
                merged.add(end, merged.own(SampleValue(track, channel.valueType, clip.duration)));
            }
        }
        merged.finish();
        return merged;
    }

    void emitChannel(const AnimChannel& channel) {
        MergedTrack merged = gather(channel);
        if (!merged.used) {
            return;
        }
        switch (channel.target.kind) {
        case TrackTarget::Kind::Node:
            emitNodeChannel(channel, merged);
            break;
        case TrackTarget::Kind::MaterialLayer:
            emitLayerChannel(channel, merged);
            break;
        case TrackTarget::Kind::MaterialFeature:
            emitFeatureChannel(channel, merged);
            break;
        case TrackTarget::Kind::Section:
            emitSectionChannel(channel, merged);
            break;
        case TrackTarget::Kind::Count:
            break;
        }
    }

    // ---- node ---------------------------------------------------------------

    mdx::Node* nodeRecord(u32 wemNode) {
        if (wemNode >= context_.nodeSlots.size()) {
            return nullptr;
        }
        const ExportContext::NodeSlot& slot = context_.nodeSlots[wemNode];
        const u32 i = slot.index;
        switch (slot.slot) {
        case ExportContext::Slot::Bone:
            return i < out_.bones.size() ? &out_.bones[i].node : nullptr;
        case ExportContext::Slot::Helper:
            return i < out_.helpers.size() ? &out_.helpers[i].node : nullptr;
        case ExportContext::Slot::Light:
            return i < out_.lights.size() ? &out_.lights[i].node : nullptr;
        case ExportContext::Slot::Attachment:
            return i < out_.attachments.size() ? &out_.attachments[i].node : nullptr;
        case ExportContext::Slot::ParticleEmitter:
            return i < out_.particleEmitters.size() ? &out_.particleEmitters[i].node : nullptr;
        case ExportContext::Slot::ParticleEmitter2:
            return i < out_.particleEmitters2.size() ? &out_.particleEmitters2[i].node : nullptr;
        case ExportContext::Slot::RibbonEmitter:
            return i < out_.ribbonEmitters.size() ? &out_.ribbonEmitters[i].node : nullptr;
        case ExportContext::Slot::CornEmitter:
            return i < out_.cornEmitters.size() ? &out_.cornEmitters[i].node : nullptr;
        case ExportContext::Slot::EventObject:
            return i < out_.eventObjects.size() ? &out_.eventObjects[i].node : nullptr;
        case ExportContext::Slot::CollisionShape:
            return i < out_.collisionShapes.size() ? &out_.collisionShapes[i].node : nullptr;
        case ExportContext::Slot::Camera:
        case ExportContext::Slot::None:
            break;
        }
        return nullptr;
    }

    void emitNodeChannel(const AnimChannel& channel, const MergedTrack& merged) {
        const u32 wemNode = channel.target.node;
        if (wemNode >= context_.nodeSlots.size()) {
            return;
        }
        const ExportContext::NodeSlot& slot = context_.nodeSlots[wemNode];

        // A camera's position is the one node track that is not on a node
        // chunk, because a camera is not one.
        if (slot.slot == ExportContext::Slot::Camera) {
            if (slot.index < out_.cameras.size() &&
                channel.target.channel == Channel::Translation) {
                Emit(merged, out_.cameras[slot.index].positionTracks);
            }
            return;
        }

        // A section whose draw M3 gates on this bone becomes a geoset
        // animation, which is where a bone's visibility ends up in a format
        // that has no per-bone one.
        if (channel.target.channel == Channel::Visibility) {
            if (VisibilityGate* gate = gateFor(wemNode)) {
                emitGate(*gate, channel, merged);
                return;
            }
        }

        if (mdx::Node* node = nodeRecord(wemNode)) {
            switch (channel.target.channel) {
            case Channel::Translation:
                Emit(merged, node->translationTracks);
                return;
            case Channel::Rotation:
                Emit(merged, node->rotationTracks);
                return;
            case Channel::Scale:
                Emit(merged, node->scalingTracks);
                return;
            default:
                break;
            }
        }

        // Everything else is a property of the record the node became.
        switch (slot.slot) {
        case ExportContext::Slot::Light: {
            if (slot.index >= out_.lights.size()) {
                return;
            }
            mdx::Light& light = out_.lights[slot.index];
            // `sub` 1 is the ambient half of the same pair โ€” the one place a
            // node animates two things of the same name.
            const bool ambient = channel.target.sub == 1;
            switch (channel.target.channel) {
            case Channel::Color: {
                mdx::Track<Vector3f>& color = ambient ? light.ambientColorTracks : light.colorTracks;
                Emit(merged, color);
                color = SwapRedBlue(std::move(color));
                return;
            }
            case Channel::Intensity:
                Emit(merged, ambient ? light.ambientIntensityTracks : light.intensityTracks);
                return;
            case Channel::AttenuationStart:
                Emit(merged, light.attenuationStartTracks);
                return;
            case Channel::AttenuationEnd:
                Emit(merged, light.attenuationEndTracks);
                return;
            case Channel::Visibility:
                Emit(merged, light.visibilityTracks);
                return;
            default:
                break;
            }
            break;
        }
        case ExportContext::Slot::Attachment:
            if (channel.target.channel == Channel::Visibility &&
                slot.index < out_.attachments.size()) {
                Emit(merged, out_.attachments[slot.index].visibilityTracks);
                return;
            }
            break;
        case ExportContext::Slot::ParticleEmitter:
            if (channel.target.channel == Channel::Visibility &&
                slot.index < out_.particleEmitters.size()) {
                Emit(merged, out_.particleEmitters[slot.index].visibilityTracks);
                return;
            }
            break;
        case ExportContext::Slot::ParticleEmitter2:
            if (channel.target.channel == Channel::Visibility &&
                slot.index < out_.particleEmitters2.size()) {
                Emit(merged, out_.particleEmitters2[slot.index].visibilityTracks);
                return;
            }
            break;
        case ExportContext::Slot::RibbonEmitter: {
            if (slot.index >= out_.ribbonEmitters.size()) {
                return;
            }
            mdx::RibbonEmitter& ribbon = out_.ribbonEmitters[slot.index];
            switch (channel.target.channel) {
            case Channel::Color:
                Emit(merged, ribbon.colorTracks);
                ribbon.colorTracks = SwapRedBlue(std::move(ribbon.colorTracks));
                return;
            case Channel::Alpha:
                Emit(merged, ribbon.alphaTracks);
                return;
            case Channel::TextureIndex:
                Emit(merged, ribbon.textureSlotTracks);
                return;
            case Channel::Visibility:
                Emit(merged, ribbon.visibilityTracks);
                return;
            default:
                break;
            }
            break;
        }
        default:
            break;
        }

        diagnostics_.warn(DiagCode::AnimTrackDropped,
                          std::string("no MDX record animates ") +
                              ToString(channel.target.channel) + " on this node",
                          ElementRef(ElementKind::Node, wemNode), profile_);
    }

    // ---- materials ----------------------------------------------------------

    mdx::Layer* layerRecord(const MaterialChannelRef& ref, u32 ordinal) {
        if (ref.profile != profile_ || ref.slot >= out_.materials.size()) {
            return nullptr;
        }
        mdx::Material& material = out_.materials[ref.slot];
        u32 layer = ordinal;
        if (ref.slot < context_.layerOfOrdinal.size()) {
            const std::vector<u32>& map = context_.layerOfOrdinal[ref.slot];
            if (ordinal < map.size()) {
                layer = map[ordinal];
            }
        }
        return layer < material.layers.size() ? &material.layers[layer] : nullptr;
    }

    /// A track that multiplies the whole material rather than one of its layers
    /// โ€” `kWholeMaterial`, which ยง10.8 introduces for exactly one case: WoW's
    /// `M2Color`, a colour and an alpha over a whole batch.
    ///
    /// MDX has no per-material tint. Its only per-draw one is `GeosetAnimation`,
    /// which keys a GEOSET, so the curve is written onto every geoset the slot
    /// draws โ€” the same record a hidden section already uses, and the same
    /// meaning: Warcraft III multiplies it into the geoset exactly as World of
    /// Warcraft multiplies `M2Color` into the batch.
    ///
    /// Not a layer track. `Layer::alphaTracks` scales one pass, and this scales
    /// all of them; routing it through `emitLayerChannel` found no ordinal
    /// `kWholeMaterial` and dropped it, which is how a lich's two effect batches
    /// โ€” each hidden by a single alpha key of zero โ€” came through as a glow and
    /// a black plane over the model.
    void emitWholeMaterialChannel(const AnimChannel& channel, const MergedTrack& merged) {
        const MaterialChannelRef& ref = channel.target.material;
        if (ref.profile != profile_) {
            return;
        }
        if (channel.target.channel != Channel::Alpha && channel.target.channel != Channel::Color) {
            diagnostics_.warn(DiagCode::AnimTrackDropped,
                              std::string("a whole-material track is ") +
                                  ToString(channel.target.channel) +
                                  ", and a geoset animation carries only colour and alpha",
                              ElementRef(ElementKind::Slot, ref.slot), profile_);
            return;
        }
        bool drawn = false;
        for (std::size_t g = 0; g < out_.geosets.size(); ++g) {
            if (out_.geosets[g].materialId != ref.slot) {
                continue;
            }
            drawn = true;
            mdx::GeosetAnimation& animation = geosetAnimationFor(static_cast<u32>(g));
            if (channel.target.channel == Channel::Alpha) {
                Emit(merged, animation.alphaTracks);
            } else {
                Emit(merged, animation.colorTracks);
                animation.colorTracks = SwapRedBlue(std::move(animation.colorTracks));
            }
        }
        if (!drawn) {
            diagnostics_.warn(DiagCode::AnimTrackDropped,
                              "no geoset draws this material slot, so its whole-material " +
                                  std::string(ToString(channel.target.channel)) +
                                  " track has nowhere to go",
                              ElementRef(ElementKind::Slot, ref.slot), profile_);
        }
    }

    void emitLayerChannel(const AnimChannel& channel, const MergedTrack& merged) {
        if (channel.target.sub == kWholeMaterial) {
            emitWholeMaterialChannel(channel, merged);
            return;
        }
        mdx::Layer* layer = layerRecord(channel.target.material, channel.target.sub);
        if (layer == nullptr) {
            // Not this profile's set, or a layer this export filtered out. The
            // first is normal โ€” a document with two sets has tracks for both.
            if (channel.target.material.profile == profile_) {
                diagnostics_.warn(
                    DiagCode::AnimTrackDropped,
                    "a layer track names ordinal " + std::to_string(channel.target.sub) +
                        ", which this material "
                        "did not write",
                    ElementRef(ElementKind::Slot, channel.target.material.slot), profile_);
            }
            return;
        }
        switch (channel.target.channel) {
        case Channel::Alpha:
            Emit(merged, layer->alphaTracks);
            return;
        case Channel::TextureIndex:
            Emit(merged, layer->textureIdTracks);
            return;
        case Channel::Emissive:
            Emit(merged, layer->emissiveGainTracks);
            return;
        default:
            break;
        }
        diagnostics_.warn(DiagCode::AnimTrackDropped,
                          std::string("an MDX layer has no ") + ToString(channel.target.channel) +
                              " track",
                          ElementRef(ElementKind::Slot, channel.target.material.slot), profile_);
    }

    /// A feature is either the layer's fresnel โ€” which lives on the layer โ€” or
    /// its UV animation, which lives in a `TextureAnimation` the layer names.
    void emitFeatureChannel(const AnimChannel& channel, const MergedTrack& merged) {
        const MaterialChannelRef& ref = channel.target.material;
        if (ref.profile != profile_) {
            return;
        }
        const Material* material = Resolve(model_, ref.slot, ref.profile, ref.look);
        if (material == nullptr) {
            return;
        }
        const MaterialFeature* feature = nullptr;
        for (const MaterialFeature& candidate : material->Common().features) {
            if (candidate.id == channel.target.sub) {
                feature = &candidate;
                break;
            }
        }
        if (feature == nullptr) {
            diagnostics_.warn(DiagCode::AnimTrackDropped,
                              "a feature track names feature " +
                                  std::to_string(channel.target.sub) +
                                  ", which the material "
                                  "does not carry",
                              ElementRef(ElementKind::Slot, ref.slot), profile_);
            return;
        }
        mdx::Layer* layer = layerRecord(ref, feature->layer);
        if (layer == nullptr) {
            return;
        }

        if (feature->kind() == FeatureKind::Fresnel) {
            switch (channel.target.channel) {
            case Channel::Color:
                Emit(merged, layer->fresnelColorTracks);
                return;
            case Channel::Alpha:
                Emit(merged, layer->fresnelAlphaTracks);
                return;
            case Channel::Weight:
                Emit(merged, layer->fresnelTeamColorTracks);
                return;
            default:
                break;
            }
            return;
        }
        if (feature->kind() != FeatureKind::UvAnimation) {
            return;
        }

        // The layer names a TXAN, or gets one: MDX keeps UV motion in a shared
        // table rather than on the layer, and a keyed feature is exactly what
        // needs an entry.
        if (layer->textureAnimationId >= out_.textureAnimations.size()) {
            layer->textureAnimationId = static_cast<u32>(out_.textureAnimations.size());
            out_.textureAnimations.emplace_back();
        }
        mdx::TextureAnimation& animation = out_.textureAnimations[layer->textureAnimationId];
        // An `.m3`-sourced channel keys the layer's own offset/angle/tiling and
        // has to be restated; one that already came from a `TextureAnimation`
        // is written as it stands.
        const bool restate = IsM3UvSpelling(channel);
        const MergedTrack converted = restate ? MdxUvTrack(merged, channel) : MergedTrack{};
        const MergedTrack& uv = restate ? converted : merged;
        switch (channel.target.channel) {
        case Channel::UvTranslate:
            Emit(uv, animation.translationTracks);
            return;
        case Channel::UvRotate:
            Emit(uv, animation.rotationTracks);
            return;
        case Channel::UvScale:
            Emit(uv, animation.scalingTracks);
            return;
        default:
            break;
        }
    }

    // ---- visibility gates ---------------------------------------------------
    //
    // M3 does not hide a geoset, it hides a BONE: a batch names one
    // (`visibilityBone`, section 5.5) and the submit loop skips the batch while
    // that bone's visibility flag is clear. Warcraft III has no such thing --
    // its one per-geoset visibility is a geoset animation's alpha -- so the gate
    // has to be resolved on the way out, from the bone the section names onto
    // the geosets that section became.
    //
    // It is not a rare shape: 18,778 of StarCraft II's 75,031 shipped batches
    // are gated and 6,901 of Heroes' 36,712, and 37% of those gates are clear at
    // rest. Left unresolved every one of them draws, which is why a Murky
    // exported with a shark and a conch shell hanging off him.

    /// One gated section, resolved to the geosets it became.
    struct VisibilityGate {
        u32 node = kInvalidNode;
        std::vector<u32> geosets;
        bool driven = false; ///< A clip keyed it, so the rest value is not the answer.
    };

    VisibilityGate* gateFor(u32 node) {
        for (VisibilityGate& gate : gates_) {
            if (gate.node == node) {
                return &gate;
            }
        }
        return nullptr;
    }

    void buildVisibilityGates() {
        for (std::size_t m = 0; m < model_.meshes.size() && m < context_.geosetsOfMesh.size();
             ++m) {
            if (m >= context_.sectionOfGeoset.size()) {
                break;
            }
            const Mesh& mesh = model_.meshes[m];
            const std::vector<u32>& geosets = context_.geosetsOfMesh[m];
            const std::vector<u32>& sections = context_.sectionOfGeoset[m];
            for (std::size_t g = 0; g < geosets.size() && g < sections.size(); ++g) {
                if (sections[g] >= mesh.sections.size()) {
                    continue;
                }
                // Never drawn beats drawn-while-visible: a gate track written
                // here would overrule the static alpha of zero the hidden
                // section already earned, because a used track wins over the
                // record's own alpha.
                if (hasFlag(mesh.sections[sections[g]].flags, SectionFlags::Hidden)) {
                    continue;
                }
                // 0xFFFF is the source's own "always drawn"; the key is absent
                // on every section no M3 import wrote.
                const i64 node =
                    mesh.sections[sections[g]].native.value(kSectionVisibilityNode, -1);
                if (node < 0 || node == kSectionAlwaysDrawn ||
                    node >= static_cast<i64>(model_.nodes.size())) {
                    continue;
                }
                VisibilityGate* gate = gateFor(static_cast<u32>(node));
                if (gate == nullptr) {
                    VisibilityGate created;
                    created.node = static_cast<u32>(node);
                    gates_.push_back(std::move(created));
                    gate = &gates_.back();
                }
                gate->geosets.push_back(geosets[g]);
            }
        }
    }

    /// The channel that drives @p node's visibility, for its rest value.
    const AnimChannel* visibilityChannelOf(u32 node) const {
        for (const AnimChannel& channel : model_.animChannels.channels) {
            if (channel.target.kind == TrackTarget::Kind::Node && channel.target.node == node &&
                channel.target.channel == Channel::Visibility) {
                return &channel;
            }
        }
        return nullptr;
    }

    /// A visibility flag written as a geoset alpha.
    ///
    /// Always as a **step**, whatever the source's AnimRef says: the step bit is
    /// set on 0 of StarCraft II's 18,778 gates and on 31 of Heroes' 6,901, and a
    /// linear ramp between 0 and 1 is a fade. The engine has no midpoint to fade
    /// through -- it samples these through the override blender, where the first
    /// contributor wins outright -- so a flag crosses as a flag.
    ///
    /// **A sequence that keys nothing gets a key anyway**, holding the rest
    /// value, because that is what such a sequence samples in M3 and MDX has one
    /// timeline where it had many: without it the previous sequence's answer
    /// leaks into the next. Only 6,068 of StarCraft II's 18,199 animated gates
    /// are keyed in every one of their model's sequences; 9,318 in some of them.
    void emitGate(VisibilityGate& gate, const AnimChannel& channel, const MergedTrack& merged) {
        gate.driven = true;

        f32 rest = 1.0f;
        if (channel.hasInitValue()) {
            std::memcpy(&rest, channel.initValue.data(), sizeof(f32));
        }
        u8 restBytes[sizeof(f32)];
        std::memcpy(restBytes, &rest, sizeof(f32));

        MergedTrack stepped = merged;
        stepped.interp = Interpolation::Step;
        if (merged.globalSequenceId == kNoGlobalSequence) {
            for (const Window& window : windows_) {
                if (window.globalSequenceId != kNoGlobalSequence) {
                    continue;
                }
                const bool keyed =
                    std::any_of(merged.times.begin(), merged.times.end(),
                                [&](u32 t) { return t >= window.start && t <= window.end; });
                if (!keyed) {
                    stepped.add(window.start, restBytes);
                }
            }
            stepped.finish();
        }

        for (const u32 geoset : gate.geosets) {
            if (geoset < out_.geosets.size()) {
                Emit(stepped, geosetAnimationFor(geoset).alphaTracks);
            }
        }
    }

    /// A gate no clip ever drove: its rest value is the whole answer, and a
    /// static alpha of zero is how MDX says "this geoset does not draw" -- the
    /// same thing a hidden section becomes. 2,813 of StarCraft II's gates are
    /// keyed by no sequence at all.
    void emitStandingVisibilityGates() {
        for (const VisibilityGate& gate : gates_) {
            if (gate.driven) {
                continue;
            }
            const AnimChannel* channel = visibilityChannelOf(gate.node);
            if (channel == nullptr || !channel->hasInitValue()) {
                continue;
            }
            f32 rest = 1.0f;
            std::memcpy(&rest, channel->initValue.data(), sizeof(f32));
            if (rest != 0.0f) {
                continue;
            }
            for (const u32 geoset : gate.geosets) {
                if (geoset < out_.geosets.size()) {
                    geosetAnimationFor(geoset).alpha = 0.0f;
                }
            }
        }
    }

    // ---- sections -----------------------------------------------------------

    /// A `GeosetAnimation` keys a geoset. One record per geoset, created on
    /// first use โ€” alpha and colour are two channels sharing it, and a hidden
    /// section already made one before the animation export ran.
    mdx::GeosetAnimation& geosetAnimationFor(u32 geoset) {
        for (mdx::GeosetAnimation& existing : out_.geosetAnimations) {
            if (existing.geosetId == geoset) {
                return existing;
            }
        }
        mdx::GeosetAnimation created;
        created.geosetId = geoset;
        created.flags = mdx::GeosetAnimation::Flag::Color;
        out_.geosetAnimations.push_back(std::move(created));
        return out_.geosetAnimations.back();
    }

    /// A section channel names a MESH, and a mesh is now several geosets โ€” so
    /// the curve is written onto each of them. Equal on a document that came
    /// from `.mdx`, where a mesh is one geoset by construction.
    void emitSectionChannel(const AnimChannel& channel, const MergedTrack& merged) {
        if (channel.target.mesh >= context_.geosetsOfMesh.size()) {
            return;
        }
        for (const u32 geoset : context_.geosetsOfMesh[channel.target.mesh]) {
            if (geoset >= out_.geosets.size()) {
                continue;
            }
            mdx::GeosetAnimation& animation = geosetAnimationFor(geoset);
            switch (channel.target.channel) {
            case Channel::Alpha:
                Emit(merged, animation.alphaTracks);
                break;
            case Channel::Color:
                Emit(merged, animation.colorTracks);
                animation.colorTracks = SwapRedBlue(std::move(animation.colorTracks));
                break;
            default:
                break;
            }
        }
    }

    // ---- UV motion that is not keyed ----------------------------------------

    /// A texture matrix MDX can hold: a turn and a scale about the texture
    /// centre, and a translation applied ahead of both.
    struct UvState {
        Vector2f scale{1, 1};
        f32 angle = 0;         ///< Radians, counter-clockwise about z.
        Vector2f column{0, 0}; ///< The affine's own translation column.
    };

    /// `TextureInput::uvTransform` read as one, or nothing when it shears.
    ///
    /// `AnimateTextureMap` composes `uv' = R * S * (uv + T - 0.5) + 0.5`, so
    /// each COLUMN of the linear block carries one axis' scale and both name
    /// the same angle. A matrix whose columns disagree -- a shear, or
    /// StarCraft II's own `S * R` under a tiling that differs per axis -- has
    /// no MDX spelling and is reported rather than quietly squared off.
    static std::optional<UvState> standingUv(const Matrix3x2f& matrix) {
        UvState state;
        state.angle = std::atan2(matrix.m[1][0], matrix.m[0][0]);
        const f32 c = std::cos(state.angle);
        const f32 s = std::sin(state.angle);
        state.scale = Vector2f{matrix.m[0][0] * c + matrix.m[1][0] * s,
                               matrix.m[1][1] * c - matrix.m[0][1] * s};
        if (std::fabs(matrix.m[0][1] + state.scale.y * s) > 1e-3f ||
            std::fabs(matrix.m[1][1] - state.scale.y * c) > 1e-3f) {
            return std::nullopt;
        }
        state.column = Vector2f{matrix.m[0][2], matrix.m[1][2]};
        return state;
    }

    /// The `UvAnimation` feature on @p ordinal that states a RATE, if any.
    static const UvAnimationFeature* constantRateUv(const CommonMaterial& common, u32 ordinal) {
        for (const MaterialFeature& feature : common.features) {
            if (feature.kind() != FeatureKind::UvAnimation || feature.layer != ordinal) {
                continue;
            }
            const auto* body = std::get_if<UvAnimationFeature>(&feature.payload);
            if (body != nullptr && body->isConstantRate()) {
                return body;
            }
        }
        return nullptr;
    }

    /// The global sequence of @p milliseconds, made on first use.
    ///
    /// A global sequence *is* a period, so two layers scrolling at the same rate
    /// share one rather than each adding a row to a chunk every reader walks.
    u32 globalSequenceOf(u32 milliseconds) {
        for (std::size_t i = 0; i < out_.globalSequences.size(); ++i) {
            if (out_.globalSequences[i] == milliseconds) {
                return static_cast<u32>(i);
            }
        }
        out_.globalSequences.push_back(milliseconds);
        return static_cast<u32>(out_.globalSequences.size() - 1);
    }

    /// MDX's `KTAT` value for a wanted translation COLUMN under @p state's
    /// turn and scale.
    ///
    /// The engine reads the track as `uv' = R * S * (uv + T - 0.5) + 0.5`, so
    /// the column a layer actually gets is `R * S * (T - 0.5) + 0.5`, and this
    /// is that read backwards. Unturned and unscaled it is the column itself,
    /// which is what every tool that treats the track as a plain scroll
    /// assumes.
    static Vector3f translationFor(const UvState& state, const Vector2f& column) {
        const f32 c = std::cos(state.angle);
        const f32 s = std::sin(state.angle);
        const f32 vx = column.x - 0.5f;
        const f32 vy = column.y - 0.5f;
        const f32 wx = c * vx + s * vy;
        const f32 wy = -s * vx + c * vy;
        return Vector3f{state.scale.x != 0.0f ? wx / state.scale.x + 0.5f : column.x,
                        state.scale.y != 0.0f ? wy / state.scale.y + 0.5f : column.y, 0.0f};
    }

    /// The period over which @p rate covers a whole number of UV tiles on every
    /// axis, so the track's last key leaves the texture where the first one
    /// found it.
    ///
    /// The slowest moving axis sets it -- one tile -- and the faster ones are
    /// rounded to the nearest whole tile within that window. Their rate is then
    /// off by at most half a tile over the whole period, and the alternative is
    /// a visible jump every time the sequence wraps.
    static f32 seamlessPeriod(const Vector2f& rate) {
        f32 period = 0.0f;
        for (const f32 axis : {rate.x, rate.y}) {
            if (axis != 0.0f) {
                period = std::max(period, 1.0f / std::abs(axis));
            }
        }
        return period;
    }

    /// Diablo III states UV motion as a RATE, and both it and StarCraft II carry
    /// a standing scale under it. MDX holds neither on the layer -- its UV state
    /// is a `TextureAnimation`, which is keys -- so both are written here, after
    /// the keyed features have taken the TXANs they need.
    ///
    /// A rate's keys ride a GLOBAL SEQUENCE because the source's clock is not the
    /// clip's: `ActorModel_ResolveSubObjectMaterials` steps the scroll off world
    /// time with a literal 1/60 s, and hanging it on a looping clip would snap
    /// every scrolling layer back at the loop point.
    void emitStandingUvTransforms() {
        for (u32 slot = 0; slot < static_cast<u32>(model_.materialSlots.size()); ++slot) {
            const Material* material = Resolve(model_, slot, profile_, 0);
            if (material == nullptr) {
                continue;
            }
            MaterialChannelRef ref;
            ref.profile = profile_;
            ref.slot = slot;
            ref.look = 0;

            const CommonMaterial& common = material->Common();
            for (u32 ordinal = 0; ordinal < common.ordinalCount(); ++ordinal) {
                mdx::Layer* layer = layerRecord(ref, ordinal);
                if (layer == nullptr || layer->textureAnimationId < out_.textureAnimations.size()) {
                    // No layer, or a keyed feature already owns its UV state.
                    continue;
                }
                const TextureInput* input = common.inputAt(ordinal);
                const UvAnimationFeature* rate = constantRateUv(common, ordinal);
                if (input == nullptr || (input->uvTransform.isIdentity() && rate == nullptr)) {
                    continue;
                }
                const std::optional<UvState> standing = standingUv(input->uvTransform);
                if (!standing.has_value()) {
                    diagnostics_.warn(DiagCode::AnimTrackDropped,
                                      "a UV transform with shear has no MDX spelling",
                                      ElementRef(ElementKind::Layer, slot, ordinal), profile_);
                    continue;
                }
                emitOneUvAnimation(*layer, *standing, rate, slot, ordinal);
            }
        }
    }

    void emitOneUvAnimation(mdx::Layer& layer, const UvState& standing,
                            const UvAnimationFeature* rate, u32 slot, u32 ordinal) {
        mdx::TextureAnimation animation;
        const Vector3f start = translationFor(standing, standing.column);
        // A turn puts a cosine of 6e-17 through every term, so "at rest" is a
        // tolerance and not an equality -- a quarter turn's translation lands
        // on 3e-17 and would otherwise write a track that says nothing.
        constexpr f32 kRest = 1e-6f;

        if (std::fabs(standing.scale.x - 1.0f) > kRest ||
            std::fabs(standing.scale.y - 1.0f) > kRest) {
            animation.scalingTracks.isUsed = true;
            animation.scalingTracks.interpolationType = mdx::InterpolationType::None;
            animation.scalingTracks.timestamps = {0};
            animation.scalingTracks.keys_data = {
                Vector3f{standing.scale.x, standing.scale.y, 1.0f}};
            animation.scalingTracks.keyCount = 1;
        }
        // A standing turn: 5981 StarCraft II layers and 15218 Heroes ones set
        // one, and MDX has nowhere but a one-key rotation track to keep it.
        if (std::fabs(standing.angle) > kRest) {
            const f32 half = standing.angle * 0.5f;
            animation.rotationTracks.isUsed = true;
            animation.rotationTracks.interpolationType = mdx::InterpolationType::None;
            animation.rotationTracks.timestamps = {0};
            animation.rotationTracks.keys_data = {
                Quaternion{0.0f, 0.0f, std::sin(half), std::cos(half)}};
            animation.rotationTracks.keyCount = 1;
        }

        u32 globalSequence = kNoGlobalSequence;
        if (rate != nullptr) {
            if (rate->scaleRate.x != 0.0f || rate->scaleRate.y != 0.0f) {
                // A scale that grows without bound has no period, so no global
                // sequence can hold it.
                diagnostics_.warn(DiagCode::AnimTrackDropped,
                                  "a UV scale RATE has no MDX spelling; only the standing scale "
                                  "was written",
                                  ElementRef(ElementKind::Layer, slot, ordinal), profile_);
            }
            const f32 period = seamlessPeriod(rate->scrollRate);
            const u32 milliseconds = Milliseconds(period);
            if (milliseconds > 0) {
                globalSequence = globalSequenceOf(milliseconds);
                const Vector2f travelled{std::round(rate->scrollRate.x * period),
                                         std::round(rate->scrollRate.y * period)};
                const Vector2f end{standing.column.x + travelled.x,
                                   standing.column.y + travelled.y};
                animation.translationTracks.isUsed = true;
                animation.translationTracks.interpolationType = mdx::InterpolationType::Linear;
                animation.translationTracks.globalSequenceId = globalSequence;
                animation.translationTracks.timestamps = {0, milliseconds};
                animation.translationTracks.keys_data = {start,
                                                         translationFor(standing, end)};
                animation.translationTracks.keyCount = 2;
            }
            if (rate->rotateRate != 0.0f) {
                emitUvRotation(animation, rate->rotateRate, standing.angle, globalSequence);
            }
        }

        if (!animation.translationTracks.isUsed &&
            (std::fabs(start.x) > kRest || std::fabs(start.y) > kRest)) {
            animation.translationTracks.isUsed = true;
            animation.translationTracks.interpolationType = mdx::InterpolationType::None;
            animation.translationTracks.timestamps = {0};
            animation.translationTracks.keys_data = {start};
            animation.translationTracks.keyCount = 1;
        }
        if (!animation.translationTracks.isUsed && !animation.scalingTracks.isUsed &&
            !animation.rotationTracks.isUsed) {
            return;
        }
        layer.textureAnimationId = static_cast<u32>(out_.textureAnimations.size());
        out_.textureAnimations.push_back(std::move(animation));
    }

    /// A turning UV, keyed at the quarter turns a slerp needs: two keys a half
    /// turn apart have no preferred direction to go round.
    ///
    /// The turn shares whatever period the scroll chose, so it is rounded to a
    /// whole number of turns within it -- a rate off by the same fraction as a
    /// scrolling axis, and for the same reason.
    void emitUvRotation(mdx::TextureAnimation& animation, f32 radiansPerSecond, f32 standingAngle,
                        u32 globalSequence) {
        constexpr f32 kTwoPi = 6.283185307179586f;
        if (globalSequence == kNoGlobalSequence) {
            globalSequence = globalSequenceOf(Milliseconds(kTwoPi / std::abs(radiansPerSecond)));
        }
        const u32 milliseconds = out_.globalSequences[globalSequence];
        const f32 period = static_cast<f32>(milliseconds) / kMilliseconds;
        const f32 turns = std::max(1.0f, std::round(std::abs(radiansPerSecond) * period / kTwoPi));
        const f32 total = turns * kTwoPi * (radiansPerSecond < 0.0f ? -1.0f : 1.0f);

        animation.rotationTracks.isUsed = true;
        animation.rotationTracks.interpolationType = mdx::InterpolationType::Linear;
        animation.rotationTracks.globalSequenceId = globalSequence;
        animation.rotationTracks.timestamps.clear();
        animation.rotationTracks.keys_data.clear();
        for (u32 step = 0; step <= 4; ++step) {
            const f32 fraction = static_cast<f32>(step) / 4.0f;
            const f32 half = (standingAngle + total * fraction) * 0.5f;
            animation.rotationTracks.timestamps.push_back(
                static_cast<u32>(static_cast<f32>(milliseconds) * fraction));
            animation.rotationTracks.keys_data.push_back(
                Quaternion{0.0f, 0.0f, std::sin(half), std::cos(half)});
        }
        animation.rotationTracks.keyCount = animation.rotationTracks.timestamps.size();
    }

    // ---- events -------------------------------------------------------------

    void emitEvents() {
        for (const Window& window : windows_) {
            const Clip& clip = document_.clips[window.clip];
            for (const ClipEvent& event : clip.events) {
                if (event.node >= context_.nodeSlots.size()) {
                    continue;
                }
                const ExportContext::NodeSlot& slot = context_.nodeSlots[event.node];
                if (slot.slot != ExportContext::Slot::EventObject ||
                    slot.index >= out_.eventObjects.size()) {
                    // The node's kind is not fixed across formats (ยง10.8): an
                    // `.m3` names the bone its SDEV key sits on. MDX has only
                    // the EventObject, so anything else has nowhere to land.
                    diagnostics_.warn(DiagCode::AnimTrackDropped,
                                      "event '" + event.name +
                                          "' fires at a node that is not an MDX event object",
                                      ElementRef(ElementKind::Node, event.node), profile_);
                    continue;
                }
                mdx::EventObject& object = out_.eventObjects[slot.index];
                object.globalSequenceId = window.globalSequenceId;
                const f32 absolute = event.time * kMilliseconds + static_cast<f32>(window.start);
                object.eventTrackTimes.push_back(
                    absolute <= 0.0f ? 0u : static_cast<u32>(absolute + 0.5f));
            }
        }
        for (mdx::EventObject& object : out_.eventObjects) {
            std::sort(object.eventTrackTimes.begin(), object.eventTrackTimes.end());
            object.eventTrackTimes.erase(
                std::unique(object.eventTrackTimes.begin(), object.eventTrackTimes.end()),
                object.eventTrackTimes.end());
        }
    }

    const Document& document_;
    const Model& model_;
    u32 modelIndex_;
    ProfileId profile_;
    const ExportContext& context_;
    mdx::Model& out_;
    Diagnostics& diagnostics_;
    std::vector<Window> windows_;
    std::vector<VisibilityGate> gates_;
};

} // namespace

void Export(const Document& document, u32 model, ProfileId profile, const ExportContext& context,
            mdx::Model& out, Diagnostics& diagnostics) {
    if (model >= document.models.size()) {
        return;
    }
    Exporter(document, model, profile, context, out, diagnostics).run();
}

} // namespace mdx_anim
} // namespace wem
} // namespace models
} // namespace whiteout