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
//! Crab sprites: their shells and claws, the crowding that fans a pile
//! out into lanes, and the walk drawn between ticks.

use super::{CreatureShadow, Tween, smoothing_alpha, tweened_pos, unturned};
use crate::app::art::Art;
use crate::app::layout::{self, TILE};
use crate::app::palette;
use crate::app::{Sim, effects};
use crate::sim::{Crab, CrabKind, Handedness};
use bevy::color::Mix;
use bevy::platform::collections::HashMap;
use bevy::prelude::*;

#[derive(Component)]
pub struct CrabSprite {
    pub id: u32,
    pub kind: CrabKind,
    /// A per-crab lift or drop on the shell colour, drawn once from the id,
    /// so twenty crabs of one kind are a crowd rather than twenty copies of
    /// one sprite. Small enough that a kind is still read by its colour.
    pub(crate) shade: f32,
}

/// How far a crab has been nudged out of a crowd, and how much smaller it
/// is drawn there, eased toward what [`crowd_target`] asks each frame so a
/// pile forming or breaking up is a drift and not a jump.
#[derive(Component, Default)]
pub struct Crowding {
    spread: Vec2,
    shrink: f32,
}

/// How close another crab has to be, centre to centre, to count as company.
const CROWD_RADIUS: f32 = TILE * 0.45;

/// How far across its heading a crab in a thick crowd is moved: the outer
/// of its five lanes, in world units.
const CROWD_SPREAD: f32 = TILE * 0.32;

/// How much smaller a crab in a thick crowd is drawn.
const CROWD_SHRINK: f32 = 0.28;

/// How crowded a crab is, 0 to 1, from how many others are within
/// [`CROWD_RADIUS`]: none is 0, three or more is a pile.
fn crowd_level(neighbours: usize) -> f32 {
    (neighbours as f32 / 3.0).min(1.0)
}

/// Which of five lanes across its heading a crab takes in a crowd, -1 to
/// 1: fixed by its id, so the same crab always moves the same way and a
/// stream fans out into a band instead of shuffling.
fn crowd_lane(id: u32) -> f32 {
    let lane = (id.wrapping_mul(2_654_435_761) >> 16) % 5;
    lane as f32 / 2.0 - 1.0
}

/// Where a crab should be drawn relative to its true place, and how much
/// smaller, given how crowded it is and which way it faces.
///
/// A crowd is where crabs are drawn on top of each other: a stream out of
/// a spawner walks single file, each half over the one ahead, and a lure
/// or Crab Mania heaps them into a pile of legs nobody can count. Moved
/// across their heading into lanes and drawn a little smaller, they read
/// as that many crabs. A crab on its own is drawn exactly where it is:
/// the offset is render-side only and never reaches the sim.
fn crowd_target(neighbours: usize, id: u32, heading: Vec2) -> (Vec2, f32) {
    let level = crowd_level(neighbours);
    let across = Vec2::new(-heading.y, heading.x);
    (
        across * crowd_lane(id) * CROWD_SPREAD * level,
        CROWD_SHRINK * level,
    )
}

/// How many other crabs are within [`CROWD_RADIUS`] of each crab, by id.
/// Bucketed by radius-sized cells, so each crab checks its own cell and the
/// eight round it rather than the whole beach.
fn count_neighbours(board: &crate::sim::Board, into: &mut HashMap<u32, usize>) {
    into.clear();
    let at: Vec<(u32, Vec2)> = board
        .crabs()
        .iter()
        .map(|crab| (crab.id, layout::pose_pos(board, crab.pose())))
        .collect();
    let cell = |p: Vec2| {
        (
            (p.x / CROWD_RADIUS).floor() as i32,
            (p.y / CROWD_RADIUS).floor() as i32,
        )
    };
    let mut cells: HashMap<(i32, i32), Vec<Vec2>> = HashMap::default();
    for &(_, p) in &at {
        cells.entry(cell(p)).or_default().push(p);
    }
    for &(id, p) in &at {
        let (cx, cy) = cell(p);
        let mut near = 0;
        for dx in -1..=1 {
            for dy in -1..=1 {
                if let Some(others) = cells.get(&(cx + dx, cy + dy)) {
                    near += others
                        .iter()
                        .filter(|o| o.distance_squared(p) < CROWD_RADIUS * CROWD_RADIUS)
                        .count();
                }
            }
        }
        // Itself, counted once in its own cell.
        into.insert(id, near.saturating_sub(1));
    }
}

/// The widest a shell strays from its kind's colour, either way.
const SHADE_SPREAD: f32 = 0.05;

/// One crab's shell: its kind's colour, nudged by its own shade.
///
/// Only the kinds a beach is *crowded* with. Twenty is never how many
/// golden crabs are on the sand, and a golden lightened by a twentieth
/// lands nearer a juvenile's pale orange than its own yellow: fifty points
/// wearing the face of two.
pub(crate) fn shell_color(kind: CrabKind, shade: f32) -> Color {
    let base = body_color(kind);
    match kind {
        CrabKind::Molting | CrabKind::Golden | CrabKind::Sparkling => base,
        CrabKind::Common | CrabKind::Juvenile | CrabKind::Giant => {
            if shade >= 0.0 {
                base.lighter(shade)
            } else {
                base.darker(-shade)
            }
        }
    }
}

/// How a molting crab's shell reads while banking one would start no lure
/// (`Board::lure_ready` false): most of the way to grey and a little
/// darker, so the beach shows that its lure is resting. Every other kind,
/// and a molt whose lure is ready, keeps its shell.
pub(crate) fn resting_shell(kind: CrabKind, shell: Color, lure_ready: bool) -> Color {
    match kind {
        CrabKind::Molting if !lure_ready => {
            let c = shell.to_srgba();
            let grey = 0.299 * c.red + 0.587 * c.green + 0.114 * c.blue;
            shell
                .mix(&Color::srgba(grey, grey, grey, c.alpha), 0.7)
                .darker(0.08)
        }
        CrabKind::Molting
        | CrabKind::Common
        | CrabKind::Juvenile
        | CrabKind::Giant
        | CrabKind::Golden
        | CrabKind::Sparkling => shell,
    }
}

/// The shade a crab is born with. A hash of the id rather than a draw from
/// [`effects::VisualRng`], so a crab keeps its shell for as long as it
/// lives however many times the sprite is rebuilt around it.
pub(crate) fn shade_of(id: u32) -> f32 {
    let mixed = id.wrapping_mul(2_654_435_761) >> 16;
    (mixed % 1000) as f32 / 1000.0 * SHADE_SPREAD * 2.0 - SHADE_SPREAD
}

const CLAW_LEFT: Color = Color::srgb(0.18, 0.49, 0.82); // blue = left-clawed
const CLAW_RIGHT: Color = Color::srgb(0.97, 0.82, 0.17); // yellow = right-clawed

/// The big claw's colour: the handedness tell. On a co-op stage
/// (`coop`, [`crate::sim::Rules::claw_hands`]) it is the paint of the
/// seat whose arrows turn that claw ([`crate::sim::seat_of_claw`]), the
/// paint those arrows wear, so each player steers the crabs in their own
/// colour, in either palette. Everywhere else, blue left and yellow right.
pub(crate) fn claw_color(handed: Handedness, coop: bool) -> Color {
    match (coop, handed) {
        (true, handed) => palette::seat_paint(crate::sim::seat_of_claw(handed)),
        (false, Handedness::Left) => CLAW_LEFT,
        (false, Handedness::Right) => CLAW_RIGHT,
    }
}

pub(crate) fn body_color(kind: CrabKind) -> Color {
    match kind {
        CrabKind::Common => Color::srgb(0.91, 0.50, 0.29),
        CrabKind::Juvenile => Color::srgb(0.96, 0.76, 0.42),
        CrabKind::Giant => Color::srgb(0.70, 0.25, 0.17),
        CrabKind::Molting => Color::srgb(0.61, 0.48, 0.82),
        CrabKind::Golden => Color::srgb(1.0, 0.88, 0.20),
        CrabKind::Sparkling => Color::srgb(0.75, 0.95, 1.0),
    }
}

/// The side of the square a crab's sprites are drawn in: the body, and the
/// big claw laid over it in the same frame. The sprites are square with
/// the legs reaching toward the corners, so the side is wider than the
/// shell's footprint ([`body_size`]), which is what the shadow is cut to.
pub(crate) fn sprite_side(kind: CrabKind) -> f32 {
    body_size(kind).x * 1.45
}

/// Which way up a crab's sprites are drawn. They are authored right-
/// handed, big claw on the crab's right; a left-handed crab is the same
/// crab mirrored across its own heading.
pub(crate) fn mirrored(handed: Handedness) -> bool {
    match handed {
        Handedness::Left => true,
        Handedness::Right => false,
    }
}

pub(crate) fn body_size(kind: CrabKind) -> Vec2 {
    match kind {
        CrabKind::Giant => Vec2::new(TILE * 0.80, TILE * 0.62),
        CrabKind::Juvenile => Vec2::new(TILE * 0.42, TILE * 0.34),
        CrabKind::Common | CrabKind::Molting | CrabKind::Golden | CrabKind::Sparkling => {
            Vec2::new(TILE * 0.56, TILE * 0.44)
        }
    }
}

/// A crab's body in `color`, at its kind's size and mirrored for its hand:
/// the sprite every crab on the beach is drawn as, walking, swept or
/// hopping into a keep.
pub(crate) fn crab_body(art: &Art, kind: CrabKind, handed: Handedness, color: Color) -> Sprite {
    Sprite {
        image: art.crab.clone(),
        color,
        custom_size: Some(Vec2::splat(sprite_side(kind))),
        flip_y: mirrored(handed),
        ..default()
    }
}

/// How far over its body a crab's big claw is drawn, as the body's child.
///
/// The smallest step that keeps the claw over its own body. A tenth, as
/// the walking and swept crabs once had it, put a hopping crab's claw at
/// the gulls' own depth, where which drew on top was left to chance.
const CLAW_LIFT: f32 = 0.01;

/// The big claw: the handedness tell, and the one thing a player reads a
/// crab by. A child of the body, `side` square like it, so it sits where
/// the body's arm reaches whatever the crab's size, and tinted by hand
/// rather than by kind.
pub(crate) fn crab_claw(
    art: &Art,
    handed: Handedness,
    coop: bool,
    side: Vec2,
) -> (Sprite, Transform) {
    (
        Sprite {
            image: art.claw.clone(),
            color: claw_color(handed, coop),
            custom_size: Some(side),
            flip_y: mirrored(handed),
            ..default()
        },
        Transform::from_translation(Vec3::new(0.0, 0.0, CLAW_LIFT)),
    )
}

/// Frames a second of a walking crab's gait: three strides a second.
pub(crate) const WALK_FPS: f32 = 12.0;

/// Where in its gait a crab is when the clock reads zero, in frames:
/// fractional, so neighbours change frame and bob at different instants.
/// A whole number of frames cancels out of the bob, and a crowd throbs in
/// unison twelve times a second.
fn gait_phase(id: u32) -> f32 {
    (id % 64) as f32 * 0.618_034 * 4.0
}

/// How much a walking crab grows at the top of each step.
const BOB: f32 = 0.035;

/// How big a walking crab is drawn `step` frames into its gait: it rides
/// up a touch with each pair of steps. On the board and on the menu's
/// postcard alike, and held level under reduced motion, where the legs
/// still change frame but the body stays put.
pub(crate) fn walk_bob(step: f32, reduced_motion: bool) -> f32 {
    if reduced_motion {
        1.0
    } else {
        1.0 + (step * std::f32::consts::PI).sin().abs() * BOB
    }
}

/// Spawn sprites for new crabs, despawn sprites for banked ones.
pub fn sync_crab_sprites(
    mut commands: Commands,
    sim: Res<Sim>,
    art: Res<Art>,
    mut live: Local<HashMap<u32, Crab>>,
    existing: Query<(Entity, &CrabSprite)>,
) {
    let board = &sim.0;
    // Reused buffer: rebuilt each frame without reallocating. Bank/eaten
    // storytelling happens in sim_events + effects; this system only keeps
    // sprites in step with the population.
    live.clear();
    live.extend(board.crabs().iter().map(|c| (c.id, *c)));
    for (entity, sprite) in &existing {
        if live.remove(&sprite.id).is_none() {
            commands.entity(entity).despawn();
        }
    }
    // Remaining entries are crabs without a sprite yet.
    for crab in live.values() {
        spawn_crab(&mut commands, &art, board, crab);
    }
}

/// Whether `board`'s claws wear their steering seat's colour
/// ([`claw_color`]): on a co-op stage, under claw-keyed arrows.
pub(crate) fn coop_claws(board: &crate::sim::Board) -> bool {
    board.rules().claw_hands.is_some()
}

/// `crab` where the board has it, shell, claw and shadow: the one crab a
/// round draws ([`sync_crab_sprites`]), and a map card's preview too
/// ([`super::spawn_creatures`]).
pub(crate) fn spawn_crab(
    commands: &mut Commands,
    art: &Art,
    board: &crate::sim::Board,
    crab: &Crab,
) -> Entity {
    let pos = layout::creature_pos(board, crab.tile, crab.dir, crab.progress);
    let size = body_size(crab.kind);
    let side = Vec2::splat(sprite_side(crab.kind));
    commands
        .spawn((
            CrabSprite {
                id: crab.id,
                kind: crab.kind,
                shade: shade_of(crab.id),
            },
            Crowding::default(),
            crab_body(
                art,
                crab.kind,
                crab.handed,
                shell_color(crab.kind, shade_of(crab.id)),
            ),
            Transform::from_translation(pos.extend(layout::z::CREATURE))
                .with_rotation(layout::dir_rotation(crab.dir)),
        ))
        .with_children(|parent| {
            parent.spawn((
                CreatureShadow,
                layout::image_sprite(
                    &art.shadow,
                    Color::WHITE,
                    Vec2::new(size.x * 1.35, size.y * 1.15),
                ),
                Transform::from_translation(Vec3::new(0.0, 0.0, -0.5)),
            ));
            parent.spawn(crab_claw(art, crab.handed, coop_claws(board), side));
        })
        .id()
}

/// A crab's sprite, as the interpolation moves and dresses it.
type CrabBody = (
    &'static CrabSprite,
    &'static mut Crowding,
    &'static mut Transform,
    &'static mut Sprite,
    &'static Children,
);

/// The crabs on screen and the shadows under them.
#[derive(bevy::ecs::system::SystemParam)]
pub struct CrabSprites<'w, 's> {
    bodies: Query<'w, 's, CrabBody, Without<CreatureShadow>>,
    shadows: Query<'w, 's, &'static mut Transform, (With<CreatureShadow>, Without<CrabSprite>)>,
}

/// Interpolate each crab sprite between its previous and current sim position.
pub fn interpolate_crabs(
    sim: Res<Sim>,
    fx: effects::Fx,
    tween: Tween,
    mut glint_clock: Local<f32>,
    mut by_id: Local<HashMap<u32, Crab>>,
    mut crowds: Local<HashMap<u32, usize>>,
    crabs: CrabSprites,
) {
    let effects::Fx {
        mut commands,
        art,
        mut rng,
        settings,
    } = fx;
    let Tween {
        time,
        fixed_time,
        mut watch,
        round,
        round_clock,
    } = tween;
    let CrabSprites {
        bodies: mut sprites,
        mut shadows,
    } = crabs;
    let board = &sim.0;
    let alpha = smoothing_alpha(board.ticks(), &mut watch, time.delta_secs(), &fixed_time);
    let stopped = !round.moving(board);
    by_id.clear();
    by_id.extend(board.crabs().iter().map(|c| (c.id, *c)));
    // Precious crabs glint on one clock: they twinkle together, and the
    // scatter `glint` puts on each star's position keeps that from reading
    // as a metronome. The clock runs with the round, so nothing sparkles
    // under a pause card or the results.
    let glint_now = round.run_clock(board, &mut glint_clock, time.delta_secs()) >= 0.22;
    if glint_now {
        *glint_clock = 0.0;
    }
    // During a molting lure every loose crab ignores arrows; tint them all
    // toward the luring player's colour so the takeover is visible.
    let lure_tint = board.lure().map(|(owner, _)| palette::player_color(owner));
    let lure_ready = board.lure_ready();
    count_neighbours(board, &mut crowds);
    // The same easing whatever the frame rate: about a third of a second
    // to settle into, or out of, a crowd.
    let ease = 1.0 - (-time.delta_secs() * 8.0).exp();
    // The molting pulse breathes with the round, like the walk.
    let pulse_at = round_clock.0;
    for (sprite, mut crowding, mut transform, mut body, children) in &mut sprites {
        let Some(crab) = by_id.get(&sprite.id) else {
            continue; // despawns this frame
        };
        let base = resting_shell(crab.kind, shell_color(crab.kind, sprite.shade), lure_ready);
        let shell = match lure_tint {
            Some(tint) => base.mix(&tint, 0.55),
            None => base,
        };
        layout::tint(&mut body, shell);
        let prev = layout::pose_pos(board, crab.prev);
        let curr = layout::pose_pos(board, crab.pose());
        let pos = tweened_pos(prev, curr, alpha);
        let (dx, dy) = crab.dir.offset();
        // Sim y runs down, world y runs up.
        let heading = Vec2::new(dx as f32, -(dy as f32));
        let neighbours = crowds.get(&sprite.id).copied().unwrap_or(0);
        let (spread, shrink) = crowd_target(neighbours, sprite.id, heading);
        let (was_spread, was_shrink) = (crowding.spread, crowding.shrink);
        crowding.spread = was_spread + (spread - was_spread) * ease;
        crowding.shrink = was_shrink + (shrink - was_shrink) * ease;
        transform.translation = (pos + crowding.spread).extend(layout::z::CREATURE);
        // Scuttle: a small heading wiggle while actually moving, phased per
        // crab so a crowd shimmers instead of marching. None under
        // reduced motion.
        let moving = prev != curr && !stopped;
        let wobble = if moving && !settings.reduced_motion {
            (time.elapsed_secs() * 11.0 + f32::from(sprite.id as u16 % 32)).sin() * 0.06
        } else {
            0.0
        };
        transform.rotation = layout::dir_rotation(crab.dir) * Quat::from_rotation_z(wobble);
        // A four-frame gait while walking, legs out of step, phased per
        // crab like the wiggle; the resting pose when standing.
        let step = time.elapsed_secs() * WALK_FPS + gait_phase(sprite.id);
        let wanted = if moving {
            &art.crab_walk[step as usize % art.crab_walk.len()]
        } else {
            &art.crab
        };
        if body.image != *wanted {
            body.image = wanted.clone();
        }
        let bob = if moving {
            walk_bob(step, settings.reduced_motion)
        } else {
            1.0
        };
        // Drawn a little smaller in a crowd, and molting crabs pulse
        // gently on top of that while their lure is ready: they are worth
        // chasing. A resting molt holds still, as it holds its colour back.
        let pulse = if sprite.kind == CrabKind::Molting && lure_ready {
            1.0 + (pulse_at * 5.0).sin() * 0.06
        } else {
            1.0
        };
        transform.scale = Vec3::splat(pulse * bob * (1.0 - crowding.shrink));
        // The shadow: pushed out from under the body, the same way as
        // every other thing standing on this sand, since one sitting
        // exactly beneath the crab is never seen.
        //
        // After the pulse, and divided by it: a child's translation is in
        // the parent's frame, so a molting crab would otherwise swing its
        // shadow in time with its own breathing.
        let body_scale = transform.scale.x.max(f32::EPSILON);
        for child in children {
            if let Ok(mut shadow) = shadows.get_mut(*child) {
                shadow.translation = unturned(&transform, layout::SUN / body_scale, -0.5);
                // The ground does not bob: the shadow keeps its size while
                // the body rides up and down above it.
                shadow.scale = Vec3::splat(1.0 / bob);
            }
        }
        // Sparkling and golden crabs actually sparkle. The golden one is
        // fifty points walking, so it draws a ribbon of sparks behind it
        // and a table of four can see which way the jackpot is heading.
        if glint_now {
            match sprite.kind {
                CrabKind::Sparkling => effects::glint(
                    &mut commands,
                    &mut rng,
                    &art,
                    curr,
                    Color::srgba(0.8, 0.95, 1.0, 0.95),
                ),
                CrabKind::Golden => {
                    effects::glint(
                        &mut commands,
                        &mut rng,
                        &art,
                        curr,
                        Color::srgba(1.0, 0.9, 0.3, 0.95),
                    );
                    if moving && !settings.reduced_motion {
                        effects::spark_trail(
                            &mut commands,
                            &mut rng,
                            &art,
                            curr - heading * TILE * 0.3,
                            -heading,
                        );
                    }
                }
                CrabKind::Common | CrabKind::Juvenile | CrabKind::Giant | CrabKind::Molting => {}
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A left-handed crab is the right-handed drawing mirrored, and the two
    /// hands wear different claws: the tell a player reads a crab by.
    #[test]
    fn a_left_handed_crab_is_the_other_one_mirrored() {
        assert!(mirrored(Handedness::Left));
        assert!(!mirrored(Handedness::Right));
        assert_ne!(
            claw_color(Handedness::Left, false),
            claw_color(Handedness::Right, false)
        );
    }

    /// On a co-op stage each claw wears the colour of the seat whose
    /// arrows turn it, the arrows' own paint ([`palette::seat_paint`], so
    /// in whichever palette is on): P1's on the left claws and P2's on the
    /// right. Solo and versus keep blue and yellow. The palette switch is
    /// a process-wide flag, left alone here so no other test sees it move.
    #[test]
    fn a_coop_claw_wears_its_steering_seats_colour() {
        use crate::app::palette;
        for handed in [Handedness::Left, Handedness::Right] {
            let seat = crate::sim::seat_of_claw(handed);
            assert_eq!(crate::sim::claw_of(seat), Some(handed));
            assert_eq!(claw_color(handed, true), palette::seat_paint(seat));
        }
        assert_ne!(
            claw_color(Handedness::Left, true),
            claw_color(Handedness::Right, true)
        );
        assert_eq!(claw_color(Handedness::Left, false), CLAW_LEFT);
        assert_eq!(claw_color(Handedness::Right, false), CLAW_RIGHT);
    }

    /// A crab's square is bigger than its shell, legs out to the corners,
    /// and the kinds keep their sizes: a giant over a common over a young.
    #[test]
    fn a_crab_is_drawn_bigger_than_its_shell_and_in_its_size() {
        for kind in CrabKind::ALL {
            assert!(sprite_side(kind) > body_size(kind).x, "{kind:?}");
        }
        let side = sprite_side;
        assert!(side(CrabKind::Giant) > side(CrabKind::Common));
        assert!(side(CrabKind::Common) > side(CrabKind::Juvenile));
    }

    /// How crowded a crab is climbs with its company and stops at full:
    /// nothing alone, a third with one neighbour, full at three, no further.
    #[test]
    fn a_crowd_fills_up_at_three_neighbours() {
        assert_eq!(crowd_level(0), 0.0);
        assert!((crowd_level(1) - 1.0 / 3.0).abs() < 1e-6);
        assert_eq!(crowd_level(3), 1.0);
        assert_eq!(crowd_level(20), 1.0);
    }

    /// A crab on its own is drawn exactly where it is; in a crowd it moves
    /// across its heading, never along it, by at most the outer lane, and
    /// always to the same side for the same crab.
    #[test]
    fn a_crowd_fans_out_across_its_heading_and_a_lone_crab_stays_put() {
        let east = Vec2::X;
        for id in 0..40 {
            assert_eq!(
                crowd_target(0, id, east),
                (Vec2::ZERO, 0.0),
                "crab {id} alone"
            );
            let (spread, shrink) = crowd_target(5, id, east);
            assert_eq!(spread.x, 0.0, "crab {id} moved along its heading");
            assert!(spread.y.abs() <= CROWD_SPREAD + 1e-4, "{spread}");
            assert_eq!(shrink, CROWD_SHRINK, "a pile is a full crowd");
            assert_eq!(
                crowd_target(5, id, east),
                (spread, shrink),
                "same crab, same lane"
            );
        }
        // One neighbour is a third of a crowd.
        let (_, some) = crowd_target(1, 3, east);
        assert!((some - CROWD_SHRINK / 3.0).abs() < 1e-6);
        // The five lanes are all in use across a crowd of crabs.
        let lanes: std::collections::BTreeSet<i32> =
            (0..40).map(|id| (crowd_lane(id) * 2.0) as i32).collect();
        assert_eq!(lanes.len(), 5, "{lanes:?}");
    }

    /// A crab keeps its shell for as long as it lives. The shade is a hash
    /// of the id rather than a draw, so a sprite rebuilt around a crab, as
    /// they constantly are, does not hand it a new colour.
    #[test]
    fn a_crab_keeps_the_shell_it_was_born_with() {
        for id in [0u32, 1, 7, 64, 1_000, 65_535, u32::MAX] {
            assert_eq!(shade_of(id), shade_of(id), "id {id} drifted");
            let shade = shade_of(id);
            assert!(
                (-SHADE_SPREAD..=SHADE_SPREAD).contains(&shade),
                "id {id} strayed off the band: {shade}"
            );
        }
    }

    /// And the crowd has to actually be a crowd: a hash that answered the
    /// same for every id would compile, pass the test above, and leave
    /// twenty identical crabs on the sand.
    #[test]
    fn a_crowd_is_not_twenty_copies_of_one_crab() {
        let shades: Vec<f32> = (0..40).map(shade_of).collect();
        let spread = shades.iter().fold(f32::MIN, |a, &b| a.max(b))
            - shades.iter().fold(f32::MAX, |a, &b| a.min(b));
        assert!(
            spread > SHADE_SPREAD,
            "forty crabs covered only {spread} of the band"
        );
    }

    /// A shell is its kind's colour, nudged - never another kind's.
    ///
    /// The kinds are told apart by colour on a crowded beach, and what that
    /// needs is not a small *number* (the nudge is a perceptual lighten, so
    /// a saturated gold moves a long way in blue for little visible change)
    /// but a guarantee about neighbours: whatever the shade does, the shell
    /// must still be nearer its own kind than any other.
    #[test]
    fn a_shade_never_carries_a_shell_into_another_kind() {
        const KINDS: [CrabKind; 6] = [
            CrabKind::Common,
            CrabKind::Juvenile,
            CrabKind::Giant,
            CrabKind::Molting,
            CrabKind::Golden,
            CrabKind::Sparkling,
        ];
        let apart = |a: Color, b: Color| {
            let (a, b) = (a.to_srgba(), b.to_srgba());
            ((a.red - b.red).powi(2) + (a.green - b.green).powi(2) + (a.blue - b.blue).powi(2))
                .sqrt()
        };
        for kind in KINDS {
            for id in 0..40u32 {
                let shell = shell_color(kind, shade_of(id));
                let own = apart(shell, body_color(kind));
                for other in KINDS.into_iter().filter(|&k| k != kind) {
                    assert!(
                        own < apart(shell, body_color(other)),
                        "a shaded {kind:?} (id {id}) is nearer {other:?} than itself"
                    );
                }
                let srgba = shell.to_srgba();
                for channel in [srgba.red, srgba.green, srgba.blue] {
                    assert!((0.0..=1.0).contains(&channel), "{kind:?} left the channel");
                }
            }
        }
    }

    /// A molt whose lure is resting is drawn greyer than one whose lure is
    /// ready, and no other kind changes with the lure.
    #[test]
    fn a_resting_molt_is_drawn_dimmed() {
        let shell = body_color(CrabKind::Molting);
        let saturation = |c: Color| {
            let c = c.to_srgba();
            let hi = c.red.max(c.green).max(c.blue);
            let lo = c.red.min(c.green).min(c.blue);
            hi - lo
        };
        assert_eq!(resting_shell(CrabKind::Molting, shell, true), shell);
        let resting = resting_shell(CrabKind::Molting, shell, false);
        assert!(saturation(resting) < saturation(shell) * 0.5, "{resting:?}");
        for kind in CrabKind::ALL {
            if kind != CrabKind::Molting {
                assert_eq!(
                    resting_shell(kind, body_color(kind), false),
                    body_color(kind)
                );
            }
        }
    }
}