pinch-points 0.9.0

A fast, kid-friendly crab-routing game: route streams of crabs into your sandcastle before time runs out
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
//! Castles: their tier-scaled keep, the pennant on top, and the shudder
//! and floating points a bank sets off.

use super::{OnTile, WALL_COLOR, clear_stale, image_sprite, on_board, z};
use crate::app::Sim;
use crate::app::art::Art;
use crate::app::layout::{self, TILE};
use crate::app::palette;
use crate::sim::{TileKind, castle_tier};
use bevy::color::Mix;
use bevy::prelude::*;

/// Marker for a castle's sprite tree; carries the tier it was built at so a
/// score crossing a threshold rebuilds it (spec §3.4: the castle grows with
/// score and doubles as the scoreboard).
#[derive(Component)]
pub struct CastleSprite {
    x: u8,
    y: u8,
    tier: u8,
    /// Whose it is. Kept because the castle wears its owner's colour and a
    /// tide event can hand it to somebody else without its tier moving: on
    /// tier alone the sprite stands in the old owner's colour until the new
    /// one scores across a threshold.
    owner: u8,
}

impl OnTile for CastleSprite {
    fn tile(&self) -> (u8, u8) {
        (self.x, self.y)
    }
}

pub fn sync_castles(
    mut commands: Commands,
    sim: Res<Sim>,
    art: Res<Art>,
    mut covered: Local<Vec<bool>>,
    existing: Query<(Entity, &CastleSprite)>,
) {
    let board = &sim.0;
    clear_stale(
        &mut commands,
        board,
        &mut covered,
        existing,
        |sprite| match board.tile_at(sprite.x, sprite.y) {
            TileKind::Castle(owner) => {
                owner == sprite.owner && castle_tier(board.scores()[owner as usize]) == sprite.tier
            }
            TileKind::Empty
            | TileKind::Rock
            | TileKind::Spawner(_)
            | TileKind::Turnstile { .. }
            | TileKind::Kelp
            | TileKind::Pool => false,
        },
    );
    for (x, y, kind) in board.tiles() {
        let idx = usize::from(board.index_of(x, y));
        if covered[idx] {
            continue;
        }
        let TileKind::Castle(owner) = kind else {
            continue;
        };
        spawn_castle(&mut commands, &art, board, (x, y), owner);
    }
}

/// `owner`'s castle on tile `(x, y)`, at the tier its score has reached:
/// the one castle a round draws ([`sync_castles`]), and a map card's
/// preview too ([`super::spawn_board_pieces`]).
pub(crate) fn spawn_castle(
    commands: &mut Commands,
    art: &Art,
    board: &crate::sim::Board,
    (x, y): (u8, u8),
    owner: u8,
) -> Entity {
    let tier = castle_tier(board.scores()[owner as usize]);
    let color = palette::player_color(owner);
    let pos = layout::tile_center(board, x, y);
    commands
        .spawn((
            CastleSprite { x, y, tier, owner },
            CastleKick(0.0),
            CastleFlinch::default(),
            Transform::from_translation(pos.extend(z::CASTLE)),
            Visibility::default(),
        ))
        .with_children(|parent| build_castle(parent, art, tier, color))
        .id()
}

/// The sand a castle is built of before its owner's colour goes in.
const SAND: Color = Color::srgb(0.925, 0.84, 0.66);

/// A castle's walls: sand, dyed well toward its owner's colour.
///
/// Not the owner's colour outright, which reads as a flat coloured square
/// on the beach. Dyed sand still says whose it is from across the board,
/// and leaves the owner's full colour for the flags and the banner, which
/// is what they are for.
pub fn castle_body(owner: Color) -> Color {
    SAND.mix(&owner, 0.62)
}

/// One of a castle's two shadows, and where it rests under the castle at
/// its own size. The castle swells when a crab banks and when it flies in
/// a swap, and its shadows, being its children, swelled and lunged out
/// along the sun with it; [`steady_castle_shadows`] holds them to the
/// ground.
#[derive(Component)]
pub struct CastleShadow {
    at: Vec3,
}

/// A castle whose scale may have moved this frame.
type SwollenCastle = (With<CastleSprite>, Changed<Transform>);

/// Keep a castle's shadows where they lie and at their size however the
/// castle swells or sways above them: their offset and size divided by its
/// scale, as a gull's are (a post's offset is too, though not yet its
/// size), and the lean and shift of a raid's sway ([`CastleFlinch`]) taken
/// back out. After the kick, the flight and the flinch, which are what
/// move it.
pub fn steady_castle_shadows(
    castles: Query<(&Transform, &CastleFlinch, &Children), SwollenCastle>,
    mut shadows: Query<(&CastleShadow, &mut Transform), Without<CastleSprite>>,
) {
    for (castle, flinch, children) in &castles {
        let scale = castle.scale.x.max(f32::EPSILON);
        let unlean = castle.rotation.inverse();
        for child in children {
            if let Ok((shadow, mut place)) = shadows.get_mut(*child) {
                let ground = shadow.at.truncate() - flinch.offset;
                let local = (unlean * ground.extend(0.0)).truncate() / scale;
                place.translation = local.extend(shadow.at.z);
                place.rotation = unlean;
                place.scale = swell(1.0 / scale);
            }
        }
    }
}

/// One piece of a castle: which sprite, how big and where, in tiles from
/// the tile's centre, and how far in front of the keep it is drawn.
struct Piece {
    size: f32,
    at: Vec2,
    z: f32,
}

/// Where a tier's keep stands and how big it is. It rises a little as the
/// castle grows, and moves back a step once there is a wall in front.
fn keep(tier: u8) -> Piece {
    let (size, lift) = match tier {
        0 => (0.66, 0.02),
        1 => (0.62, 0.08),
        2 => (0.64, 0.08),
        _ => (0.72, 0.10),
    };
    Piece {
        size,
        at: Vec2::new(0.0, lift),
        z: 0.0,
    }
}

/// The corner towers a tier has: the front pair from tier 2, the back pair
/// from tier 3. Back towers stand behind the keep and front ones before
/// the wall, which is what makes it read as a courtyard.
fn turrets(tier: u8) -> Vec<Piece> {
    let mut towers = Vec::new();
    for (from, y, z) in [(3, 0.30, -0.15), (2, -0.30, 0.2)] {
        if tier >= from {
            for side in [-1.0, 1.0] {
                towers.push(Piece {
                    size: 0.36,
                    at: Vec2::new(side * 0.40, y),
                    z,
                });
            }
        }
    }
    towers
}

/// How far above its centre a tower's top stands, as a fraction of its
/// sprite: the top merlons in `tools/gen_sprites.py`.
const TOWER_TOP: f32 = 0.27;

/// Everything standing on a castle's tile at `tier`: its shadow on the
/// sand, and its [`castle_parts`].
pub(crate) fn build_castle(parent: &mut ChildSpawnerCommands, art: &Art, tier: u8, color: Color) {
    let footprint = if tier == 0 { 0.8 } else { 1.15 };
    // It sits on the sand rather than in it.
    parent.spawn((
        CastleShadow {
            at: layout::SUN.extend(-0.4),
        },
        image_sprite(
            &art.shadow,
            Color::srgba(1.0, 1.0, 1.0, 0.7),
            Vec2::splat(TILE * footprint),
        ),
        Transform::from_translation(layout::SUN.extend(-0.4)),
    ));
    // And the shadow its height throws, long along the sun: the castle is
    // the tallest thing on the beach, and grows taller with each tier.
    let (sprite, place) = super::cast_shadow(
        art,
        Vec3::new(0.0, 0.0, -0.41),
        super::Caster {
            footprint: TILE * footprint,
            height: TILE * (0.14 + 0.05 * f32::from(tier)),
            alpha: 0.45,
        },
    );
    parent.spawn((
        CastleShadow {
            at: place.translation,
        },
        sprite,
        place,
    ));
    for part in castle_parts(art, tier, color) {
        let at = (part.at * TILE).extend(part.z);
        let size = part.size * TILE;
        let sprite = match &part.image {
            Some(image) => image_sprite(image, part.tint, size),
            None => Sprite::from_color(part.tint, size),
        };
        let mut piece =
            parent.spawn((sprite, PartTint(part.tint), Transform::from_translation(at)));
        if part.pennant {
            piece.insert(Pennant);
        }
    }
}

/// One piece of a castle, wherever it is drawn: on its tile, or on the
/// results card that shows off the winner's.
pub(crate) struct CastlePart {
    /// The sprite, or `None` for a plain block of `tint`: a flag's pole or
    /// its pennant.
    pub image: Option<Handle<Image>>,
    pub tint: Color,
    /// Width and height, in tiles.
    pub size: Vec2,
    /// Its centre, in tiles from the castle's, y up.
    pub at: Vec2,
    /// Depth among the castle's own pieces: higher is nearer.
    pub z: f32,
    /// Whether it is a pennant, which waves.
    pub pennant: bool,
}

/// Every piece of a castle at `tier` in its owner's `color`, back to front
/// (spec §3.4: the castle grows with its owner's score and is the
/// scoreboard):
///
/// | tier | points | adds |
/// |---|---|---|
/// | 0 | 0-9 | the keep and its flag |
/// | 1 | 10-24 | a curtain wall, gate at the front |
/// | 2 | 25-49 | two front towers, flying pennants |
/// | 3 | 50+ | two back towers, a taller keep, a moat |
///
/// Each tier adds pieces and none replaces one, so a castle only ever
/// gets bigger: a keep that grew instead would cover the wall it stands
/// inside by tier 3, and the tiers would be hard to tell apart at a
/// glance. Everything but the sand shadow under it, which
/// belongs to the beach rather than to the castle.
pub(crate) fn castle_parts(art: &Art, tier: u8, color: Color) -> Vec<CastlePart> {
    let body = castle_body(color);
    let mut parts = Vec::new();
    let mut add = |image: &Handle<Image>, tint: Color, piece: &Piece| {
        parts.push(CastlePart {
            image: Some(image.clone()),
            tint,
            size: Vec2::splat(piece.size),
            at: piece.at,
            z: piece.z,
            pennant: false,
        });
    };
    let whole = |z| Piece {
        size: 0.96,
        at: Vec2::ZERO,
        z,
    };
    if tier >= 3 {
        // The moat, dug outermost: water, open in the middle.
        add(
            &art.moat,
            Color::WHITE,
            &Piece {
                size: 1.22,
                at: Vec2::ZERO,
                z: -0.3,
            },
        );
    }
    if tier >= 1 {
        add(&art.wall_back, body, &whole(-0.2));
    }
    let keep = keep(tier);
    add(&art.castle, body, &keep);
    // The owner's banner on the keep, and its door's arch, in full colour.
    add(
        &art.castle_trim,
        color.lighter(0.12),
        &Piece { z: 0.05, ..keep },
    );
    if tier >= 1 {
        add(&art.wall_front, body, &whole(0.1));
    }
    let towers = turrets(tier);
    for tower in &towers {
        add(&art.turret, body, tower);
    }
    for tower in &towers {
        let top = tower.at + Vec2::new(0.0, tower.size * TOWER_TOP);
        flag(&mut parts, color, top, 0.16, 0.6, tower.z + 0.05);
    }
    // The flag (spec §3.4: flying their colour flag): a driftwood pole
    // with a bright owner-coloured pennant, sticking up past the keep so
    // it reads at a glance.
    flag(
        &mut parts,
        color,
        keep.at + Vec2::new(-0.06, keep.size * TOWER_TOP),
        KEEP_POLE,
        1.3,
        0.3,
    );
    parts.sort_by(|a, b| a.z.total_cmp(&b.z));
    parts
}

/// How far above its castle a flag is drawn: from the castle's layer up to
/// the flags' own ([`z::FLAG`]), over the fences and whatever stands in the
/// row above.
const FLAG_LIFT: f32 = z::FLAG - z::CASTLE;

/// How a flag's depth among its castle's pieces is kept above the lift:
/// pressed into a sliver, so the flags keep their order among themselves
/// and stay under the crown.
const FLAG_DEPTH: f32 = 0.1;

/// A pole standing on `base` (tiles from the castle's centre), `height`
/// tiles tall, with a pennant of `scale` times the keep's first one, at
/// depth `z` among the castle's flags, drawn on the flags' layer.
fn flag(parts: &mut Vec<CastlePart>, color: Color, base: Vec2, height: f32, scale: f32, z: f32) {
    let z = FLAG_LIFT + FLAG_DEPTH * z;
    parts.push(CastlePart {
        image: None,
        tint: WALL_COLOR,
        size: Vec2::new(2.5 / TILE, height),
        at: Vec2::new(base.x, base.y + height / 2.0),
        z,
        pennant: false,
    });
    let size = Vec2::new(0.20, 0.12) * scale;
    parts.push(CastlePart {
        image: None,
        // The owner's colour as it is: the castle is dyed sand now, and a
        // lightened pennant, which stood out against a castle already in
        // that colour, washed out to white on a yellow one.
        tint: color,
        size,
        at: Vec2::new(base.x + size.x / 2.0, base.y + height - size.y / 2.0),
        z,
        pennant: true,
    });
}

/// How high over a castle's centre its leader's crown floats, in tiles:
/// clear above the top of the keep's flagpole, which rises with the tier.
fn crown_lift(tier: u8) -> f32 {
    let keep = keep(tier);
    keep.at.y + keep.size * TOWER_TOP + KEEP_POLE + CROWN_SIZE * 0.32
}

/// How tall the keep's flagpole stands, in tiles.
const KEEP_POLE: f32 = 0.36;

/// How big the leader's crown is drawn, in tiles (the sprite is square,
/// the crown in it a little smaller).
const CROWN_SIZE: f32 = 0.5;

/// The crown floating over a leading castle, by the tile the castle
/// stands on, and how long it has been up, for its arrival.
#[derive(Component)]
pub struct CastleCrown {
    x: u8,
    y: u8,
    age: f32,
}

/// What `crown_the_leader` reads: who sits at the table, and how.
#[derive(bevy::ecs::system::SystemParam)]
pub struct Table<'w> {
    screen: Res<'w, State<crate::app::Screen>>,
    seats: Res<'w, crate::app::Seats>,
    scoring: crate::app::teams::Scoring<'w>,
    time: Res<'w, Time>,
    clock: Res<'w, crate::app::round_state::RoundClock>,
}

/// Float a crown over the castle of whoever leads, so the board itself
/// says who is winning: a judge watching the beach could not tell without
/// looking across at the scores.
///
/// The leader is the score panel's own ([`Scoring::leaders`]): the one
/// top scorer, or every castle of the leading team, and nobody at zero or
/// in a tie, so the board's crown and the panel's never disagree. Versus
/// only: a puzzle has no one to lead. A new leader's crown drops in with a
/// little bounce, held still under reduced motion; it follows its castle
/// through a swap's flight.
///
/// [`Scoring::leaders`]: crate::app::teams::Scoring::leaders
pub fn crown_the_leader(
    mut commands: Commands,
    sim: Res<Sim>,
    art: Res<Art>,
    table: Table,
    castles: Query<(&CastleSprite, &Transform), Without<CastleCrown>>,
    mut crowns: Query<(Entity, &mut CastleCrown, &mut Transform), Without<CastleSprite>>,
) {
    let board = &sim.0;
    let versus = *table.screen.get() == crate::app::Screen::Versus;
    let leaders = table.scoring.leaders(board.scores(), table.seats.0);
    let leading = |c: &CastleSprite| versus && leaders[usize::from(c.owner)];
    // A crown whose castle no longer leads, or is gone, goes.
    for (entity, crown, _) in &crowns {
        let kept = castles
            .iter()
            .any(|(c, _)| c.x == crown.x && c.y == crown.y && leading(c));
        if !kept {
            commands.entity(entity).despawn();
        }
    }
    let calm = table.scoring.local.settings.reduced_motion;
    let dt = table.time.delta_secs();
    // The bob breathes with the round: still under a pause card and on
    // the results.
    let now = table.clock.0;
    for (castle, place) in &castles {
        if !leading(castle) {
            continue;
        }
        let over = place.translation.truncate()
            + Vec2::new(0.0, crown_lift(castle.tier) * TILE * place.scale.y);
        let found = crowns
            .iter_mut()
            .find(|(_, crown, _)| crown.x == castle.x && crown.y == castle.y);
        let Some((_, mut crown, mut at)) = found else {
            commands.spawn((
                super::BoardStatic,
                CastleCrown {
                    x: castle.x,
                    y: castle.y,
                    age: 0.0,
                },
                image_sprite(&art.crown, Color::WHITE, Vec2::splat(CROWN_SIZE * TILE)),
                Transform::from_translation(over.extend(z::CROWN))
                    .with_scale(Vec3::splat(if calm { 1.0 } else { 0.0 })),
            ));
            continue;
        };
        crown.age += dt;
        let (drop, grow) = if calm { (0.0, 1.0) } else { arrival(crown.age) };
        // A slow breath once it has landed, so it reads as floating.
        let bob = if calm { 0.0 } else { (now * 2.2).sin() * 1.5 };
        at.translation = (over + Vec2::new(0.0, drop * TILE + bob)).extend(z::CROWN);
        at.scale = Vec3::splat(grow);
    }
}

/// A new leader's crown arriving `age` seconds in: how far above its
/// resting place it is, in tiles, and how big, dropping in over a third of
/// a second and settling with a small bounce.
fn arrival(age: f32) -> (f32, f32) {
    const DROP: f32 = 0.35;
    let t = (age / DROP).clamp(0.0, 1.0);
    // Ease-out-back: overshoots a touch, then settles.
    let back = 1.0 + 2.7 * (t - 1.0).powi(3) + 1.7 * (t - 1.0).powi(2);
    ((1.0 - t) * 0.4, back)
}

/// A castle's flag; waves gently in the sea breeze.
#[derive(Component)]
pub struct Pennant;

/// A scale wobble on a castle when a crab banks there (the original's
/// rocket shudder). Set to 1.0 on a bank, decays to rest.
#[derive(Component)]
pub struct CastleKick(pub f32);

/// How long the castles are in the air when the tide swaps them.
const FLIGHT: f32 = 1.1;

/// How much bigger a castle looks at the top of its flight. The path is a
/// straight line, so this is the only thing saying it is off the ground
/// rather than sliding along the sand.
const RISE: f32 = 0.30;

/// The swap animation: how long is left, and where each castle is flying
/// from.
///
/// A resource and not a component because a castle changing hands is
/// rebuilt by [`sync_castles`] mid-flight (new owner, new colour, often a
/// new tier), and a component would go down with the entity it was on.
#[derive(Resource, Default)]
pub struct CastleFlight {
    left: f32,
    /// Where each castle in the air set off from. Empty when none is.
    from: Vec<Flight>,
}

/// One castle's journey: the tile it is landing on, and where it left.
pub struct Flight {
    tile: (u8, u8),
    from: Vec2,
}

/// The swap detector's memory: the castles as they stood last frame, and
/// which board they stood on.
///
/// The board is what tells a new layout from a swap. Without it a match
/// that ended on a CastleSwap leaves the swapped layout here, and the next
/// round on the same map reads as a swap on its first frame; a round
/// pasted in mid-clock did the same, since its clock had not rolled back.
#[derive(Default)]
pub struct Detector {
    /// The [`BoardGeneration`] the castles in `held` were read off.
    ///
    /// [`BoardGeneration`]: crate::app::sim_events::BoardGeneration
    board: crate::app::sim_events::BoardStamp,
    held: Vec<Held>,
}

/// A castle as the swap detector sees it: whose it is, and where.
///
/// Named because the comparison that spots a swap is about which of these
/// changed and which did not, and in `(u8, u8, u8)` the two coordinates and
/// the owner are the same type.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Held {
    x: u8,
    y: u8,
    owner: u8,
}

/// A castle (or a piece under one) drawn `scale` times its size across the
/// sand, and never in depth.
///
/// A scale in depth would scale its pieces' depths with it: the flags,
/// lifted to [`z::FLAG`] from the castle's own layer, rose over the
/// cursors on a castle swelling with a bank or in a swap's flight.
fn swell(scale: f32) -> Vec3 {
    Vec3::new(scale, scale, 1.0)
}

/// Where a castle is, and how big it looks, `progress` of the way from
/// `from` to `home`.
///
/// Split out because it has to start exactly on one tile and finish exactly
/// on the other, or a castle lands off its own sand.
fn hop(from: Vec2, home: Vec2, progress: f32) -> (Vec2, f32) {
    // A straight line between the two tiles, eased out of the launch and
    // into the landing so it reads as a thing setting off and arriving
    // rather than a thing being dragged.
    let eased = progress * progress * (3.0 - 2.0 * progress);
    // Up off the sand and back down onto it, in scale alone: zero at both
    // ends, so the castle finishes exactly the size it started.
    let height = (progress * std::f32::consts::PI).sin();
    (from.lerp(home, eased), 1.0 + RISE * height)
}

/// Fly the castles to their new places when the tide swaps them round.
///
/// The sim hands each castle to the next owner where it stands: nothing
/// moves, the colours change. That is right for the round and wrong for
/// the eye, so the render layer says it the other way about: your castle
/// *travels* to where the next one was, over the sand, and lands wearing
/// the colour it took off in.
///
/// The swap is spotted by watching the board rather than by listening for
/// the tide event. The event is raised by the snapshot comparison a tick
/// behind the board it describes, so by the time it arrives a castle asked
/// where it came from answers "here"; watching for the same castles on the
/// same tiles under different owners cannot be mistimed.
///
/// Runs after [`kick_castles`], which also writes scale: a bank landing in
/// the same frame as a swap should not fight the flight for the transform.
///
/// A new board (see [`BoardGeneration`]) empties both the memory and any
/// flight still in the air, so a round that ends mid-swap leaves nothing
/// to land on the next beach. Done here rather than on screen exit because
/// a rematch on the same map is a board swap with no screen change in it.
///
/// [`BoardGeneration`]: crate::app::sim_events::BoardGeneration
pub fn fly_castles(
    time: Res<Time>,
    current: crate::app::sim_events::CurrentBoard,
    settings: Res<crate::app::settings::GameSettings>,
    mut flight: ResMut<CastleFlight>,
    mut before: Local<Detector>,
    // Swapped with the last reading rather than built fresh each frame.
    mut now: Local<Vec<Held>>,
    mut castles: Query<(&CastleSprite, &mut Transform)>,
) {
    let board = &current.sim.0;
    if before.board.is_new(&current) {
        before.held.clear();
        flight.from.clear();
        flight.left = 0.0;
    }
    now.clear();
    now.extend(board.tiles().filter_map(|(x, y, kind)| match kind {
        TileKind::Castle(owner) => Some(Held { x, y, owner }),
        TileKind::Empty
        | TileKind::Rock
        | TileKind::Spawner(_)
        | TileKind::Turnstile { .. }
        | TileKind::Kelp
        | TileKind::Pool => None,
    }));
    if swapped(&before.held, &now) && !settings.reduced_motion {
        flight.from.clear();
        let mut old = before.held.clone();
        for held in now.iter() {
            // An owner with two castles has them paired in board order,
            // which is arbitrary but consistent, and nothing crosses.
            if let Some(at) = old.iter().position(|was| was.owner == held.owner) {
                let was = old.remove(at);
                flight.from.push(Flight {
                    tile: (held.x, held.y),
                    from: layout::tile_center(board, was.x, was.y),
                });
            }
        }
        flight.left = FLIGHT;
    }
    std::mem::swap(&mut before.held, &mut now);
    if flight.left <= 0.0 {
        return;
    }
    flight.left = (flight.left - time.delta_secs()).max(0.0);
    let progress = 1.0 - flight.left / FLIGHT;
    for (sprite, mut transform) in &mut castles {
        let home = layout::tile_center(board, sprite.x, sprite.y);
        let from = flight
            .from
            .iter()
            .find(|flight| flight.tile == (sprite.x, sprite.y))
            .map_or(home, |flight| flight.from);
        let (at, scale) = hop(from, home, progress);
        transform.translation.x = at.x;
        transform.translation.y = at.y;
        transform.scale = swell(scale);
    }
    if flight.left == 0.0 {
        // Landed: hand the transform back exactly as it was found, so
        // nothing downstream inherits a fraction of a scale.
        flight.from.clear();
        for (sprite, mut transform) in &mut castles {
            let home = layout::tile_center(board, sprite.x, sprite.y);
            transform.translation = home.extend(transform.translation.z);
            transform.scale = Vec3::ONE;
        }
    }
}

/// Whether the castles changed hands: the same tiles holding the same
/// owners between them, dealt out differently.
///
/// Deliberately narrow: a castle built, a castle lost or a score crossing a
/// tier all change this list too, and only a permutation of who holds what
/// is a swap.
fn swapped(before: &[Held], now: &[Held]) -> bool {
    if before.len() < 2 || before.len() != now.len() || before == now {
        return false;
    }
    let tiles = |list: &[Held]| {
        let mut out: Vec<(u8, u8)> = list.iter().map(|held| (held.x, held.y)).collect();
        out.sort_unstable();
        out
    };
    let owners = |list: &[Held]| {
        let mut out: Vec<u8> = list.iter().map(|held| held.owner).collect();
        out.sort_unstable();
        out
    };
    tiles(before) == tiles(now) && owners(before) == owners(now)
}

/// What each keep banked over one frame's events, added up, as the keep's
/// centre and its total.
///
/// The sim reports a bank per crab, and a castle can take several on one
/// tick: eight, measured over a set of six-seat rounds. [`score_pip`] has
/// no jitter in it, so a pip per crab puts eight identical `+1`s pixel on
/// pixel and the player who banked eight reads one `+1` drawn too dark.
///
/// Summed instead: `+8` is the number that happened, and this is the only
/// place it is ever shown.
///
/// Per keep and not per seat: a seat can hold two castles (some of the
/// shipped puzzles give the first seat two), and summed by owner both
/// of them bounced and floated the pair's total, so a crab walking into
/// one castle was shown arriving at both, at twice its worth.
///
/// [`score_pip`]: crate::app::effects::score_pip
fn gains<'a>(
    events: impl IntoIterator<Item = &'a crate::app::sim_events::SimEvent>,
) -> Vec<(Vec2, i32)> {
    use crate::app::sim_events::SimEvent;
    let mut gained: Vec<(Vec2, i32)> = Vec::new();
    for event in events {
        let SimEvent::CrabBanked { keep, points, .. } = event else {
            continue;
        };
        match gained.iter_mut().find(|(at, _)| same_keep(*at, *keep)) {
            Some((_, total)) => *total = total.saturating_add(*points),
            None => gained.push((*keep, *points)),
        }
    }
    gained
}

/// Whether two board positions name the same keep: a bank's `keep` and a
/// castle sprite's tile centre come out of the same `tile_center`, so
/// anything within a fraction of a tile is the one castle.
fn same_keep(a: Vec2, b: Vec2) -> bool {
    a.distance_squared(b) < (TILE * 0.25).powi(2)
}

/// What the keep at `at` banked this frame, out of [`gains`].
fn gained_at(gained: &[(Vec2, i32)], at: Vec2) -> i32 {
    gained
        .iter()
        .find(|(keep, _)| same_keep(*keep, at))
        .map_or(0, |(_, points)| *points)
}

/// Bounce the castle whose keep is at `keep`: a crab has just landed in
/// it. Sent from the hop that carries the crab in (`effects::advance_hops`)
/// rather than from the bank, which the sim reports while the crab is
/// still on the doorstep.
pub(crate) fn kick_keep(
    board: &crate::sim::Board,
    castles: &mut Query<(&CastleSprite, &mut CastleKick)>,
    keep: Vec2,
) {
    for (sprite, mut kick) in castles.iter_mut() {
        if on_board(board, sprite.x, sprite.y)
            && same_keep(layout::tile_center(board, sprite.x, sprite.y), keep)
        {
            kick.0 = 1.0;
        }
    }
}

/// Float the points a castle's banks made (or cost) over its keep, in the
/// owner's colour, the moment the sim scores them, and play out the bounce
/// [`kick_keep`] starts when each crab lands. The bounce holds still under
/// a pause card, with the rest of the round.
pub fn kick_castles(
    mut commands: Commands,
    mut events: MessageReader<crate::app::sim_events::SimEvent>,
    sim: Res<Sim>,
    time: Res<Time>,
    round: crate::app::round_state::RoundState,
    mut castles: Query<(&CastleSprite, &mut CastleKick, &mut Transform)>,
) {
    let board = &sim.0;
    // Reduced motion keeps the floating points and drops the bounce, which
    // it does by itself: no crab hops in to start one.
    let gained = gains(events.read());
    for (sprite, _, _) in &castles {
        // A stranded sprite (off this board) is `sync_castles`'s to
        // remove; it has no tile to read.
        if !on_board(board, sprite.x, sprite.y) {
            continue;
        }
        let TileKind::Castle(owner) = board.tile_at(sprite.x, sprite.y) else {
            continue;
        };
        let at = layout::tile_center(board, sprite.x, sprite.y);
        let points = gained_at(&gained, at);
        if points == 0 {
            continue;
        }
        crate::app::effects::score_pip(
            &mut commands,
            // Signed: a left claw banked under a Right Claws call costs.
            format!("{points:+}"),
            at + Vec2::new(0.0, TILE * 0.35),
            palette::player_color(owner).lighter(0.15),
        );
    }
    if round.held() {
        return;
    }
    let dt = time.delta_secs();
    for (_, mut kick, mut transform) in &mut castles {
        if kick.0 <= 0.0 {
            continue;
        }
        kick.0 = (kick.0 - dt * 3.2).max(0.0);
        // A quick squash-and-settle: overshoot then ease back.
        let wobble = 1.0 + 0.20 * kick.0 * (kick.0 * std::f32::consts::PI * 2.0).sin().abs();
        transform.scale = swell(wobble);
    }
}

/// A piece of a castle's own colour, kept so the piece can be darkened
/// and brought back exactly: a raid shades the whole castle for a moment.
#[derive(Component)]
pub struct PartTint(Color);

/// A castle's flinch when a gull raids it: seconds `since` the raid while
/// it plays, and the sway it is drawn with this frame, `lean` radians about
/// its foot and the `offset` that keeps the foot planted.
/// [`steady_castle_shadows`] reads both back out of the shadows.
#[derive(Component, Default)]
pub struct CastleFlinch {
    since: Option<f32>,
    lean: f32,
    offset: Vec2,
}

/// How long a castle flinches: the sway has settled by then and the shade
/// gone. The last crumbs it shed lie on a little after.
const FLINCH: f32 = 1.6;

/// How far a raided castle leans at most, how fast its sway dies and how
/// often it swings, a little over twice a second.
const SWAY_LEAN: f32 = 7.0 * std::f32::consts::PI / 180.0;
const SWAY_DECAY: f32 = 3.4;
const SWAY_HZ: f32 = 2.3;

/// How dark a raid shades a castle at most.
const FLINCH_SHADE: f32 = 0.34;

/// Where a castle sways from, below its tile's centre: the keep's foot,
/// where it meets the sand.
const FOOT: f32 = 0.25;

/// When the grains come off a raided castle's rim, in seconds after the
/// raid, and how many each time: a first fall with the hit, then a few
/// stragglers as it rocks.
const CRUMB_WAVES: [(f32, usize); 4] = [(0.04, 5), (0.30, 3), (0.48, 2), (0.66, 2)];

/// A raided castle's lean `since` seconds after the raid: a swing about
/// its foot that dies away.
fn sway(since: f32) -> f32 {
    SWAY_LEAN * (-SWAY_DECAY * since).exp() * (std::f32::consts::TAU * SWAY_HZ * since).sin()
}

/// How dark a raided castle is `since` seconds after the raid: dark at
/// once, in a few hundredths of a second, then back over most of one.
fn flinch_shade(since: f32) -> f32 {
    use crate::app::effects::smoothstep;
    FLINCH_SHADE * (since / 0.06).min(1.0) * (1.0 - smoothstep((since - 0.1) / 0.85))
}

/// Where a castle leaning `lean` radians at `scale` is moved to keep its
/// foot planted while it sways. Not swaying (settled, under reduced motion,
/// or while a castle swap flies it, which sets its own scale), it stays on
/// its tile's centre exactly, for the kick and the flight to scale it about
/// as they always have, and its shadows stay put under it.
fn planted(lean: f32, scale: f32, swaying: bool) -> Vec2 {
    if !swaying {
        return Vec2::ZERO;
    }
    let foot = Vec2::new(0.0, -FOOT * TILE);
    foot - (Quat::from_rotation_z(lean) * (foot * scale).extend(0.0)).truncate()
}

/// A castle's part tint darkened by `shade`, its alpha kept.
fn shaded(tint: Color, shade: f32) -> Color {
    let c = tint.to_srgba();
    let keep = 1.0 - shade;
    Color::srgba(c.red * keep, c.green * keep, c.blue * keep, c.alpha)
}

/// Shake a castle when a gull raids it, on top of the raid's flash, ring
/// and pip: it sways about its foot and swings back to rest, its flag
/// flung the other way, it darkens for a moment, and grains of its sand
/// fall off the rim to lie at its foot before they sink away. The castle
/// takes the hit, rather than the tile it stands on.
///
/// Reduced motion keeps the darkening, which is a colour and not a motion,
/// and drops the sway and the sand. Held under a pause like the rest of
/// the round, and still during a castle swap's flight, which moves the
/// castle itself.
#[allow(clippy::too_many_arguments)]
pub fn flinch_castles(
    fx: crate::app::effects::Fx,
    mut events: MessageReader<crate::app::sim_events::SimEvent>,
    sim: Res<Sim>,
    time: Res<Time>,
    round: crate::app::round_state::RoundState,
    flight: Res<CastleFlight>,
    mut castles: Query<(&CastleSprite, &mut CastleFlinch, &mut Transform, &Children)>,
    mut parts: Query<(&PartTint, &mut Sprite)>,
) {
    use crate::app::sim_events::SimEvent;
    let crate::app::effects::Fx {
        mut commands,
        art,
        mut rng,
        settings,
    } = fx;
    let board = &sim.0;
    let calm = settings.reduced_motion;
    for event in events.read() {
        let SimEvent::CastleRaided { pos, .. } = event else {
            continue;
        };
        for (sprite, mut flinch, _, _) in &mut castles {
            if on_board(board, sprite.x, sprite.y)
                && same_keep(layout::tile_center(board, sprite.x, sprite.y), *pos)
            {
                flinch.since = Some(0.0);
            }
        }
    }
    if round.held() {
        return;
    }
    let dt = time.delta_secs();
    for (sprite, mut flinch, mut transform, children) in &mut castles {
        let Some(before) = flinch.since else {
            continue;
        };
        let since = before + dt;
        let done = since >= FLINCH;
        flinch.since = (!done).then_some(since);
        let shade = if done { 0.0 } else { flinch_shade(since) };
        for child in children {
            if let Ok((tint, mut piece)) = parts.get_mut(*child) {
                piece.color = shaded(tint.0, shade);
            }
        }
        let still = calm || done || flight.left > 0.0 || !on_board(board, sprite.x, sprite.y);
        flinch.lean = if still { 0.0 } else { sway(since) };
        let lean = Quat::from_rotation_z(flinch.lean);
        flinch.offset = planted(flinch.lean, transform.scale.x, !(done || still));
        if flight.left <= 0.0 && on_board(board, sprite.x, sprite.y) {
            let home = layout::tile_center(board, sprite.x, sprite.y);
            transform.translation = (home + flinch.offset).extend(transform.translation.z);
            transform.rotation = lean;
        }
        if calm {
            continue;
        }
        let keep = keep(sprite.tier);
        let center = layout::tile_center(board, sprite.x, sprite.y);
        for (at, count) in CRUMB_WAVES {
            if before < at && at <= since {
                crate::app::effects::crumbs(
                    &mut commands,
                    &mut rng,
                    &art,
                    &crate::app::effects::Crumbs {
                        // Off the rim as it leans: the top swings out
                        // further than the foot.
                        rim: center
                            + Vec2::new(
                                -flinch.lean.sin() * TILE * 0.33,
                                (keep.at.y + keep.size * 0.30) * TILE,
                            ),
                        foot: center.y - FOOT * TILE,
                        body: castle_body(palette::player_color(sprite.owner)),
                        count,
                        life: 1.5 - at,
                    },
                );
            }
        }
    }
}

/// A castle that just grew says so.
///
/// [`castle_tier`] is the whole scoreboard (spec §3.4), and without this a
/// castle crossing a threshold changes shape between one frame and the next
/// with nothing to mark it.
///
/// Runs after [`sync_castles`], and must: the sprite being cheered is the
/// one built at the *new* tier, and the events reaching this frame are the
/// previous frame's (see the `Frame` sets), so it is already standing.
///
/// The ring and the sand go up at once, with the new shape they mark,
/// which the castle takes on the frame the score crosses. The bounce waits
/// for the crab: a keep a crab banked into this frame bounces when that
/// crab lands in it ([`kick_keep`]), as every bank does, and bounced here
/// as well it celebrated while the crab still stood on the doorstep.
pub fn cheer_tier_ups(
    fx: crate::app::effects::Fx,
    mut events: MessageReader<crate::app::sim_events::SimEvent>,
    sim: Res<Sim>,
    mut trauma: ResMut<crate::app::effects::Trauma>,
    mut castles: Query<(&CastleSprite, &mut CastleKick)>,
) {
    use crate::app::effects::{Burst, Fx, burst, ring};
    let Fx {
        mut commands,
        art,
        mut rng,
        settings,
    } = fx;
    use crate::app::sim_events::SimEvent;
    let board = &sim.0;
    let events: Vec<&SimEvent> = events.read().collect();
    // The keeps a crab is on its way into, which bounce as it lands.
    let landing: Vec<Vec2> = events
        .iter()
        .filter_map(|event| {
            let SimEvent::CrabBanked { keep, points, .. } = event else {
                return None;
            };
            (*points > 0).then_some(*keep)
        })
        .collect();
    for event in &events {
        let SimEvent::TierUp { owner } = event else {
            continue;
        };
        // The growth itself is the news and it survives reduced motion;
        // only the fireworks over it stand down.
        if settings.reduced_motion {
            continue;
        }
        for (sprite, mut kick) in &mut castles {
            if sprite.owner != *owner || !on_board(board, sprite.x, sprite.y) {
                continue;
            }
            let at = layout::tile_center(board, sprite.x, sprite.y);
            let color = palette::player_color(*owner);
            ring(
                &mut commands,
                &art,
                at,
                color.lighter(0.25),
                TILE * 0.8,
                2.6,
                0.55,
            );
            burst(
                &mut commands,
                &mut rng,
                &Burst {
                    image: art.puff.clone(),
                    pos: at,
                    color: Color::srgba(0.95, 0.9, 0.76, 0.9),
                    count: 9,
                    size: 15.0,
                    speed: 62.0,
                    gravity: 55.0,
                },
            );
            // Grains of the new work trickling off its walls: small, quick
            // to fall, in the castle's own dyed sand, out of its top.
            burst(
                &mut commands,
                &mut rng,
                &Burst {
                    image: art.puff.clone(),
                    pos: at + Vec2::new(0.0, TILE * 0.25),
                    color: castle_body(color),
                    count: 12,
                    size: 5.0,
                    speed: 70.0,
                    gravity: 170.0,
                },
            );
            for _ in 0..4 {
                crate::app::effects::glint(&mut commands, &mut rng, &art, at, color.lighter(0.4));
            }
            if !landing.iter().any(|keep| same_keep(*keep, at)) {
                kick.0 = 1.0;
            }
        }
        trauma.add(0.2);
    }
}

/// Flutter every pennant: a small shear-like x-scale ripple plus a slight
/// tilt, phased per entity so flags do not wave in lockstep. With less
/// motion asked for, every flag hangs at rest, as it is spawned.
pub fn wave_pennants(
    time: Res<Time>,
    settings: Res<crate::app::settings::GameSettings>,
    castles: Query<&CastleFlinch>,
    mut flags: Query<(Entity, &mut Transform, &ChildOf), With<Pennant>>,
) {
    let t = time.elapsed_secs();
    for (entity, mut transform, castle) in &mut flags {
        // A castle swaying after a raid flings its flag the other way.
        let fling = castles
            .get(castle.parent())
            .map_or(0.0, |flinch| -2.0 * flinch.lean);
        let (stretch, tilt) = if settings.reduced_motion {
            (1.0, 0.0)
        } else {
            let phase = f32::from(entity.to_bits() as u16 % 17);
            (
                1.0 + (t * 5.0 + phase).sin() * 0.12,
                (t * 3.0 + phase).sin() * 0.08,
            )
        };
        transform.scale.x = stretch;
        transform.rotation = Quat::from_rotation_z(tilt + fling);
    }
}

#[cfg(test)]
mod tests {
    use super::{
        FLINCH, FLINCH_SHADE, SWAY_LEAN, castle_body, castle_parts, flinch_shade, gained_at, gains,
        hop, keep, sway, turrets,
    };

    /// A raided castle darkens at once and comes back, and sways about its
    /// foot in a swing that dies away: upright at the hit, never past its
    /// lean, all but still by the end of the flinch, and not darkened then.
    #[test]
    fn a_raided_castle_darkens_and_sways_back_to_rest() {
        assert_eq!(sway(0.0), 0.0, "upright at the hit");
        assert_eq!(flinch_shade(0.0), 0.0);
        assert!(
            (flinch_shade(0.08) - FLINCH_SHADE).abs() < 1e-6,
            "dark at once"
        );
        assert_eq!(flinch_shade(1.0), 0.0, "and back within the second");
        let mut swung = (0.0f32, 0.0f32);
        for frame in 0..100 {
            let since = frame as f32 / 60.0;
            let lean = sway(since);
            assert!(lean.abs() <= SWAY_LEAN, "{lean} at {since}");
            swung = (swung.0.min(lean), swung.1.max(lean));
        }
        assert!(
            swung.0 < -0.02 && swung.1 > 0.02,
            "it swings both ways: {swung:?}"
        );
        assert!(sway(FLINCH).abs() < 0.01, "and has all but settled");
    }

    /// A new leader's crown starts small and above its place and comes to
    /// rest at full size exactly on it, and it floats clear of the keep's
    /// flag at every tier.
    #[test]
    fn the_crown_lands_on_its_place_above_the_flag() {
        use super::{CROWN_SIZE, KEEP_POLE, TOWER_TOP, arrival, crown_lift};
        let (drop, grow) = arrival(0.0);
        assert!(
            drop > 0.0 && grow < 0.05,
            "arrives from above, small: {drop} {grow}"
        );
        assert_eq!(
            arrival(1.0),
            (0.0, 1.0),
            "and rests at full size on its place"
        );
        for tier in 0..=3 {
            let keep = keep(tier);
            let pole_top = keep.at.y + keep.size * TOWER_TOP + KEEP_POLE;
            let crown_foot = crown_lift(tier) - CROWN_SIZE * 0.5 * 0.7;
            assert!(
                crown_foot > pole_top - 0.02,
                "tier {tier}: crown on the flag"
            );
        }
    }

    /// With less motion asked for, the castles' flags hang still.
    #[test]
    fn pennants_hang_still_for_less_motion() {
        use super::{Pennant, wave_pennants};
        use bevy::prelude::*;
        let mut app = App::new();
        app.init_resource::<Time>();
        app.insert_resource(crate::app::settings::GameSettings {
            reduced_motion: true,
            ..Default::default()
        });
        app.add_systems(Update, wave_pennants);
        let flags: Vec<Entity> = (0..5)
            .map(|_| app.world_mut().spawn((Pennant, Transform::default())).id())
            .collect();
        app.update();
        for flag in flags {
            let at = app.world().get::<Transform>(flag).expect("a flag");
            assert_eq!(*at, Transform::default(), "{flag:?} waved");
        }
    }

    /// A castle swelling with a bank, or leaning over its foot after a
    /// raid, leaves its shadows lying where they were, at their own size
    /// and square to the sun: the ground does not swell or sway.
    #[test]
    fn a_swelling_or_swaying_castle_leaves_its_shadow_on_the_ground() {
        use super::{CastleFlinch, CastleShadow, CastleSprite, steady_castle_shadows};
        use bevy::prelude::*;
        let at = Vec3::new(15.0, -21.0, -0.41);
        for lean in [0.0f32, 0.1, -0.12] {
            let mut app = App::new();
            let scale = 1.25;
            let turn = Quat::from_rotation_z(lean);
            let offset = Vec2::new(4.0, -1.5);
            let castle = app
                .world_mut()
                .spawn((
                    CastleSprite {
                        x: 0,
                        y: 0,
                        tier: 3,
                        owner: 0,
                    },
                    CastleFlinch {
                        since: Some(0.2),
                        lean,
                        offset,
                    },
                    Transform::from_translation(offset.extend(0.0))
                        .with_rotation(turn)
                        .with_scale(Vec3::splat(scale)),
                ))
                .id();
            let shadow = app
                .world_mut()
                .spawn((
                    CastleShadow { at },
                    Transform::from_translation(at),
                    ChildOf(castle),
                ))
                .id();
            app.add_systems(Update, steady_castle_shadows);
            app.update();
            let place = *app.world().get::<Transform>(shadow).expect("the shadow");
            // Where the parent puts it, on a castle whose resting place is
            // the origin.
            let drawn =
                offset + (turn * (place.translation.truncate() * scale).extend(0.0)).truncate();
            assert!(
                (drawn - at.truncate()).length() < 1e-3,
                "lean {lean}: it lunged to {drawn}"
            );
            assert!(
                (place.scale.x * scale - 1.0).abs() < 1e-4,
                "it grew to {}",
                place.scale.x
            );
            assert!(
                (turn * place.rotation).angle_between(Quat::IDENTITY) < 1e-4,
                "lean {lean}: it turned with the castle"
            );
        }
    }
    use crate::app::art::Art;
    use crate::app::palette;

    fn parts(tier: u8) -> Vec<super::CastlePart> {
        castle_parts(&Art::blank(), tier, palette::player_color(0))
    }

    /// Every tier draws more than the last: the scoreboard only grows.
    #[test]
    fn each_tier_draws_more_than_the_last() {
        let counts: Vec<usize> = (0..=3).map(|tier| parts(tier).len()).collect();
        assert!(counts.windows(2).all(|w| w[0] < w[1]), "{counts:?}");
    }

    /// The moat is the top tier's, and only the top tier's: it is the one
    /// piece drawn wider than the tile.
    #[test]
    fn only_the_top_tier_digs_a_moat() {
        let moats = |tier| parts(tier).iter().filter(|p| p.size.x > 1.0).count();
        assert_eq!([moats(0), moats(1), moats(2), moats(3)], [0, 0, 0, 1]);
    }

    /// Every tower flies a pennant of its own, and the keep flies one more.
    #[test]
    fn every_tower_flies_a_pennant() {
        for tier in 0..=3 {
            let pennants = parts(tier).iter().filter(|p| p.pennant).count();
            assert_eq!(pennants, turrets(tier).len() + 1, "tier {tier}");
        }
    }

    /// Every flag, pole and pennant, of every tier is drawn over the fences
    /// and their corner posts, the posts and creatures in the row above
    /// and a gull flying in over the beach's edge excepted, and under the
    /// crown; every other piece stays under the posts and creatures.
    #[test]
    fn the_flags_fly_over_the_fences() {
        use crate::app::layout::z;
        for tier in 0..=3 {
            let parts = parts(tier);
            let flags: Vec<&super::CastlePart> =
                parts.iter().filter(|p| p.image.is_none()).collect();
            assert_eq!(flags.len(), 2 * (turrets(tier).len() + 1), "tier {tier}");
            for flag in flags {
                let drawn = z::CASTLE + flag.z;
                assert!(
                    drawn > z::WALL + 0.1 && drawn < z::CROWN,
                    "tier {tier}: a flag at {drawn}"
                );
            }
            for piece in parts.iter().filter(|p| p.image.is_some()) {
                assert!(
                    z::CASTLE + piece.z < z::SIGNPOST,
                    "tier {tier}: a piece at {}",
                    z::CASTLE + piece.z
                );
            }
        }
    }

    /// A castle swelling with a bank or at the top of a swap's flight keeps
    /// its flags on their layer: grown across the sand, never in depth.
    #[test]
    fn a_swollen_castle_keeps_its_flags_on_their_layer() {
        use super::{Pennant, RISE, build_castle, swell};
        use crate::app::layout::z;
        use bevy::ecs::system::RunSystemOnce;
        for scale in [1.0, 1.0 + RISE, 1.2, 1.0 / (1.0 + RISE)] {
            let mut app = App::new();
            app.add_plugins(TransformPlugin);
            app.world_mut()
                .run_system_once(move |mut commands: Commands| {
                    commands
                        .spawn(
                            Transform::from_translation(Vec3::new(0.0, 0.0, z::CASTLE))
                                .with_scale(swell(scale)),
                        )
                        .with_children(|castle| {
                            build_castle(castle, &Art::blank(), 3, palette::player_color(0));
                        });
                })
                .expect("a castle");
            app.update();
            let world = app.world_mut();
            let mut pennants = world.query_filtered::<&GlobalTransform, With<Pennant>>();
            let depths: Vec<f32> = pennants.iter(world).map(|at| at.translation().z).collect();
            assert_eq!(depths.len(), turrets(3).len() + 1);
            for drawn in depths {
                assert!(
                    drawn > z::WALL + 0.1 && drawn < z::CROWN,
                    "at {scale}x a flag at {drawn}"
                );
            }
        }
        // The flight is what reaches the largest of those scales.
        let (_, top) = hop(Vec2::ZERO, Vec2::X, 0.5);
        assert!((top - (1.0 + RISE)).abs() < 1e-5);
    }

    /// The parts come back to front: the order the results card draws them
    /// in, which UI takes from the order they are spawned.
    #[test]
    fn a_castle_comes_back_to_front() {
        for tier in 0..=3 {
            let depths: Vec<f32> = parts(tier).iter().map(|p| p.z).collect();
            assert!(
                depths.windows(2).all(|w| w[0] <= w[1]),
                "tier {tier}: {depths:?}"
            );
        }
    }

    /// A castle is sand dyed toward its owner, not the owner's colour
    /// outright, and the dye still keeps any two owners apart.
    #[test]
    fn a_castle_is_dyed_sand() {
        let bodies: Vec<Color> = (0..6)
            .map(|seat| castle_body(palette::player_color(seat)))
            .collect();
        for (seat, body) in bodies.iter().enumerate() {
            assert_ne!(
                *body,
                palette::player_color(seat as u8),
                "seat {seat} is raw colour"
            );
            for other in &bodies[seat + 1..] {
                assert_ne!(body, other, "two owners dye alike");
            }
        }
    }
    use crate::app::sim_events::SimEvent;
    use crate::sim::CrabKind;
    use bevy::prelude::*;

    /// A castle only ever gains pieces: every tier keeps the towers the
    /// last one had, going none, none, two, four, and the top tier's keep
    /// stands taller than a bare one. (Tiers 1 and 2 step the keep down a
    /// little, to fit it inside the wall they add.)
    #[test]
    fn every_tier_adds_to_the_castle() {
        let towers: Vec<usize> = (0..=3).map(|tier| turrets(tier).len()).collect();
        assert_eq!(towers, [0, 0, 2, 4]);
        for tier in 1..=3 {
            let before: Vec<_> = turrets(tier - 1).iter().map(|t| t.at).collect();
            let now: Vec<_> = turrets(tier).iter().map(|t| t.at).collect();
            assert!(
                before.iter().all(|at| now.contains(at)),
                "tier {tier} lost a tower"
            );
        }
        assert!(
            keep(3).size > keep(0).size,
            "the top tier's keep stands taller"
        );
    }

    /// A crab worth `points` walking into the keep at `keep`.
    fn bank(owner: u8, keep: Vec2, points: i32) -> SimEvent {
        SimEvent::CrabBanked {
            id: 0,
            owner,
            pos: Vec2::ZERO,
            keep,
            points,
            kind: CrabKind::Common,
            handed: crate::sim::Handedness::Right,
        }
    }

    /// The floating number is the only place a bank's worth is ever shown,
    /// so on a frame that banked eight it has to say eight.
    ///
    /// Said as `+1` eight times it lands in the same place at the same
    /// speed, since `score_pip` has no jitter: the copies rise as one and
    /// the number is simply wrong, drawn a little too dark.
    #[test]
    fn a_frame_of_banks_floats_one_number_and_it_is_the_total() {
        let keep = Vec2::new(64.0, -32.0);
        assert!(gains([]).is_empty(), "a quiet frame gains nobody");
        assert_eq!(gained_at(&gains(&[bank(1, keep, 3)]), keep), 3);
        let stream: Vec<SimEvent> = (0..8).map(|_| bank(1, keep, 1)).collect();
        assert_eq!(
            gained_at(&gains(&stream), keep),
            8,
            "eight into one keep is eight, not eight ones"
        );
        // Crabs are not all worth the same, so this is a sum and not a
        // count: a golden one is fifty walking.
        let golden = gains(&[bank(2, keep, 50), bank(2, keep, 1)]);
        assert_eq!(gained_at(&golden, keep), 51);
    }

    /// Keeps are added up apart, the two of one seat's included. A puzzle
    /// that gives the first seat two castles floated the pair's total over
    /// both of them, as if every crab had walked into each.
    #[test]
    fn every_keep_is_counted_on_its_own_even_two_of_one_seat() {
        let (left, right, far) = (
            Vec2::new(-200.0, 0.0),
            Vec2::new(200.0, 0.0),
            Vec2::new(0.0, 150.0),
        );
        let frame = vec![
            bank(0, left, 1),
            bank(0, right, 2),
            bank(0, left, 4),
            bank(3, far, 1),
        ];
        let gained = gains(&frame);
        assert_eq!(gained_at(&gained, left), 5, "two crabs home on the left");
        assert_eq!(gained_at(&gained, right), 2, "and one on the right");
        assert_eq!(gained_at(&gained, far), 1, "a rival's keep is its own");
        assert_eq!(
            gained_at(&gained, Vec2::new(0.0, -150.0)),
            0,
            "and a keep that banked nothing floats nothing"
        );
        let total: i32 = gained.iter().map(|(_, points)| points).sum();
        assert_eq!(total, 8, "nothing counted twice");
    }

    /// The two ends are the point: a castle that lands a few pixels off
    /// its tile stays there until something else redraws it.
    #[test]
    fn a_hop_starts_and_finishes_on_the_sand() {
        let from = Vec2::new(-100.0, 40.0);
        let home = Vec2::new(220.0, -60.0);
        let (start, start_scale) = hop(from, home, 0.0);
        assert_eq!(start, from);
        assert!((start_scale - 1.0).abs() < 1e-6);
        let (end, end_scale) = hop(from, home, 1.0);
        assert!(end.distance(home) < 1e-3, "{end:?} vs {home:?}");
        assert!((end_scale - 1.0).abs() < 1e-6);
    }

    /// Only a permutation is a swap. A castle built, lost, or crossing a
    /// tier changes the list too, and animating those as flights would
    /// have castles sliding in from wherever the last one happened to be.
    #[test]
    fn only_a_reshuffle_counts_as_a_swap() {
        let held = |x, y, owner| super::Held { x, y, owner };
        let a = vec![held(1, 1, 0), held(5, 1, 1)];
        let swapped_pair = vec![held(1, 1, 1), held(5, 1, 0)];
        assert!(super::swapped(&a, &swapped_pair));
        assert!(!super::swapped(&a, &a), "nothing moved");
        assert!(!super::swapped(&[], &a), "the first frame is not a swap");
        assert!(
            !super::swapped(&a, &[held(1, 1, 0), held(5, 1, 1), held(9, 1, 2)]),
            "a castle was built"
        );
        assert!(
            !super::swapped(&a, &[held(1, 1, 0), held(7, 1, 1)]),
            "a castle moved tile, which the sim never does"
        );
        assert!(
            !super::swapped(&a, &[held(1, 1, 0), held(5, 1, 2)]),
            "a different owner turned up"
        );
        assert!(
            !super::swapped(&[held(1, 1, 0)], &[held(1, 1, 1)]),
            "one castle cannot swap with itself"
        );
    }

    /// Straight between the two tiles, never off the line: a castle that
    /// bowed upwards would fly over the wall on a corner-to-corner swap.
    #[test]
    fn a_hop_travels_in_a_straight_line() {
        let from = Vec2::new(0.0, 0.0);
        let home = Vec2::new(400.0, 200.0);
        for step in 0..=10 {
            let progress = step as f32 / 10.0;
            let (at, _) = hop(from, home, progress);
            // Every point is on the segment: y is exactly half of x, which
            // is what the two ends say it should be.
            assert!((at.y - at.x * 0.5).abs() < 1e-3, "{at:?} at {progress}");
        }
        // And it is off the ground in between, which is the only thing
        // saying it is flying rather than sliding.
        assert!(hop(from, home, 0.5).1 > 1.0);
    }

    /// A board with seat 0's castle at (1, 1), and an app holding it.
    fn castle_stage() -> (App, Vec2) {
        let mut board = crate::sim::Board::new(5, 5, 1);
        board.set_tile(1, 1, crate::sim::TileKind::Castle(0));
        let keep = crate::app::layout::tile_center(&board, 1, 1);
        let mut app = App::new();
        app.insert_resource(crate::app::Sim(board));
        app.insert_resource(Art::blank());
        app.init_resource::<crate::app::effects::VisualRng>();
        app.init_resource::<crate::app::effects::Trauma>();
        app.init_resource::<crate::app::settings::GameSettings>();
        app.init_resource::<Time>();
        app.add_message::<SimEvent>();
        (app, keep)
    }

    fn castle_at_one_one() -> super::CastleSprite {
        super::CastleSprite {
            x: 1,
            y: 1,
            tier: 1,
            owner: 0,
        }
    }

    /// A bank that crosses a tier grows the castle at once, and the castle
    /// bounces when the crab lands in it, not before: on the bank, it
    /// bounced while the crab was still cheering on its doorstep. A tier
    /// crossed with no crab on its way in still bounces at once.
    #[test]
    fn a_tier_up_bounces_the_castle_when_its_crab_lands() {
        use super::{CastleKick, cheer_tier_ups};
        for crab in [true, false] {
            let (mut app, keep) = castle_stage();
            app.add_systems(Update, cheer_tier_ups);
            let castle = app
                .world_mut()
                .spawn((castle_at_one_one(), CastleKick(0.0)))
                .id();
            if crab {
                app.world_mut().write_message(bank(0, keep, 1));
            }
            app.world_mut().write_message(SimEvent::TierUp { owner: 0 });
            app.update();
            let kick = app.world().get::<CastleKick>(castle).expect("a castle").0;
            match crab {
                true => assert_eq!(kick, 0.0, "it waits for the crab to land"),
                false => assert_eq!(kick, 1.0, "nothing to wait for"),
            }
        }
    }

    /// A raided castle that a castle swap is flying keeps its foot where
    /// the flight puts it: the flight swells it, and taken for a sway the
    /// swell moved it off its place and its shadows with it.
    #[test]
    fn a_flying_castle_is_not_moved_to_plant_its_foot() {
        use super::{CastleFlight, CastleFlinch, flinch_castles};
        use crate::app::{Screen, VersusPhase};
        let (mut app, _) = castle_stage();
        app.insert_resource(CastleFlight {
            left: 0.5,
            from: Vec::new(),
        });
        app.insert_resource(State::new(Screen::Versus));
        app.insert_resource(State::new(VersusPhase::Running));
        app.init_resource::<crate::app::Paused>();
        app.init_resource::<crate::app::pause::PauseMenu>();
        app.init_resource::<crate::app::net::Online>();
        app.add_systems(Update, flinch_castles);
        let castle = app
            .world_mut()
            .spawn((
                castle_at_one_one(),
                CastleFlinch {
                    since: Some(0.2),
                    lean: 0.0,
                    offset: Vec2::ZERO,
                },
                Transform::from_scale(Vec3::splat(1.3)),
            ))
            .id();
        app.world_mut()
            .spawn((Transform::default(), ChildOf(castle)));
        app.update();
        let flinch = app.world().get::<CastleFlinch>(castle).expect("a castle");
        assert!(flinch.since.is_some(), "still flinching");
        assert_eq!(flinch.offset, Vec2::ZERO);
    }
}