kaeru 0.1.8

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
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
//! The frog that `kaeru install` starts with: a tadpole swims in from the
//! side, turns to face you, grows legs, loses its tail and turns into kaeru's
//! frog, which hops and blinks.
//!
//! Each frame is drawn from a small scene of lit, rounded shapes, not from
//! stored pictures, so that the motion stays smooth at any frame rate. The
//! tadpole's parts turn into the frog's step by step: its head into the
//! body, its small black eyes into the frog's eyes, so that nothing pops in.
//! The shapes are drawn with Braille characters, which have two by four dots
//! each, so that edges are finer than whole characters. A cell can also get
//! a background color, so that it shows two colors, such as a pupil in an
//! eye.

use std::f64::consts::PI;
use std::time::Duration;

/// How many columns the frog takes.
pub const COLUMNS: u16 = 28;

/// How many rows the frog takes.
pub const ROWS: u16 = 10;

/// How long one frame shows: 20 frames a second.
pub const FRAME: Duration = Duration::from_millis(50);

/// How long the animation runs, in seconds.
pub const LENGTH: f64 = 3.8;

/// One character of a frame: a Braille character's dots and its colors.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Cell {
    /// The dots that are set, as the bits of the Unicode Braille block. No
    /// dots means an empty cell.
    pub dots: u8,
    /// The color of the dots.
    pub fg: [u8; 3],
    /// The color behind the dots, when the whole cell is covered.
    pub bg: Option<[u8; 3]>,
}

impl Cell {
    /// Returns the Braille character with this cell's dots.
    pub fn symbol(self) -> char {
        char::from_u32(0x2800 + u32::from(self.dots))
            .expect("the Braille block has a character for every set of dots")
    }
}

/// The bit of each dot of a Braille character, by row and then column.
const DOT_BITS: [u8; 8] = [1, 8, 2, 16, 4, 32, 64, 128];

/// What a point of the scene is made of. Points of one material in a cell
/// share a color, so that small parts, such as a pupil, keep their shape.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Material {
    Skin,
    Tail,
    Belly,
    Mouth,
    EyeWhite,
    Pupil,
    Shine,
}

/// The tadpole's dark olive skin, which turns into the frog's green.
const TADPOLE: [f64; 3] = [112.0, 118.0, 82.0];
const SKIN: [f64; 3] = [104.0, 186.0, 84.0];
const TAIL: [f64; 3] = [138.0, 142.0, 104.0];
const BELLY: [f64; 3] = [200.0, 228.0, 146.0];
const MOUTH: [f64; 3] = [38.0, 82.0, 40.0];
const EYE_WHITE: [f64; 3] = [246.0, 244.0, 226.0];
const PUPIL: [f64; 3] = [22.0, 26.0, 22.0];
const SHINE: [f64; 3] = [255.0, 255.0, 255.0];

/// A point of the scene that is drawn: its material and its lit color.
type Hit = (Material, [f64; 3]);

/// Where everything is at one moment of the animation.
#[derive(Debug, Clone, Copy)]
struct Pose {
    /// How much of the tadpole shows while it appears, from 0 to 1.
    appear: f64,
    /// The middle of the head, which becomes the frog's body.
    center: [f64; 2],
    /// How far the body tilts, in radians, clockwise.
    tilt: f64,
    /// How far the tadpole is turned away from you, in radians: a quarter
    /// turn while it swims to the right, and 0 once it faces you.
    yaw: f64,
    /// How far the tadpole has turned into the frog, from 0 to 1.
    morph: f64,
    /// How far the back legs and the front legs have grown, from 0 to 1.
    back: f64,
    front: f64,
    /// How much of the tail is left, from 0 to 1.
    tail: f64,
    /// Where the tail's wave is, in radians.
    wave: f64,
    /// How far the frog is above where it sits.
    lift: f64,
    /// How much the frog is squashed: wider and lower above 0, and taller
    /// and thinner below 0.
    squash: f64,
    /// How far the frog's eyes are closed, from 0 to 1.
    blink: f64,
}

/// Returns 0 before 0 and 1 after 1, and eases smoothly in between.
fn smooth(value: f64) -> f64 {
    let t = value.clamp(0.0, 1.0);
    t * t * t * (t * (t * 6.0 - 15.0) + 10.0)
}

/// Returns how far `t` is from `start` to `end`, eased.
fn span(t: f64, start: f64, end: f64) -> f64 {
    smooth((t - start) / (end - start))
}

/// Returns a bump that rises from 0 at `start` to 1 halfway and falls back to
/// 0 at `end`.
fn bump(t: f64, start: f64, end: f64) -> f64 {
    let x = ((t - start) / (end - start)).clamp(0.0, 1.0);
    (x * PI).sin()
}

/// Returns the number `amount` of the way from `a` to `b`.
fn lerp(a: f64, b: f64, amount: f64) -> f64 {
    a + (b - a) * amount
}

/// Returns the point `amount` of the way from `a` to `b`.
fn lerp2(a: [f64; 2], b: [f64; 2], amount: f64) -> [f64; 2] {
    [lerp(a[0], b[0], amount), lerp(a[1], b[1], amount)]
}

/// Returns the color `amount` of the way from `a` to `b`.
fn lerp3(a: [f64; 3], b: [f64; 3], amount: f64) -> [f64; 3] {
    std::array::from_fn(|channel| lerp(a[channel], b[channel], amount))
}

/// Returns how far a leg has popped out at `t`: it grows from 0 at `start`,
/// a little past its size, and springs back to 1 at `end`.
fn pop(t: f64, start: f64, end: f64) -> f64 {
    let x = ((t - start) / (end - start)).clamp(0.0, 1.0) - 1.0;
    let spring = 2.2;
    1.0 + (spring + 1.0) * x * x * x + spring * x * x
}

/// Where the frog's body is when it sits.
const BODY: [f64; 2] = [0.0, 0.2];

/// Where the frog's feet are, which it squashes and lands on.
const FEET: [f64; 2] = [0.0, 0.9];

/// Returns where everything is `t` seconds into the animation.
fn pose(t: f64) -> Pose {
    // The tadpole swims in from the left, bobbing a little, which tilts it
    // up and down, and slows down in the middle.
    let u = smooth(t / 1.1);
    let bob = 2.0 * PI * 0.9 * t;
    let here = [lerp(-1.25, 0.0, u), 0.1 * bob.sin() * (1.0 - u)];
    let wave = 2.0 * PI * 3.2 * t;
    let morph = span(t, 1.9, 2.65);
    let tilt = 0.25 * bob.cos() * (1.0 - u) + 0.05 * wave.sin() * (1.0 - morph);
    // The back legs pop out first, then the front legs, which push out
    // through the skin with a small jolt, and then the tail shrinks away.
    let jolt = 0.06 * bump(t, 1.7, 1.88);
    // The frog hops once it has grown, and lands with a bounce.
    let landed = t - 3.1;
    let bounce = if landed > 0.0 {
        0.14 * (-6.0 * landed).exp() * (2.0 * PI * 2.6 * landed).sin()
    } else {
        0.0
    };
    Pose {
        appear: span(t, 0.0, 0.4),
        center: lerp2(here, BODY, morph),
        tilt,
        yaw: PI / 2.0 * (1.0 - span(t, 0.85, 1.4)),
        morph,
        back: pop(t, 1.35, 1.65),
        front: pop(t, 1.7, 1.95),
        tail: 1.0 - span(t, 1.8, 2.5),
        wave,
        lift: -0.2 * bump(t, 2.75, 3.1),
        squash: jolt + bounce - 0.08 * bump(t, 2.75, 3.1),
        blink: bump(t, 3.4, 3.65),
    }
}

/// Returns a number from 0 to 1 that looks random but is always the same for
/// the same two numbers.
fn noise(a: i64, b: i64) -> f64 {
    let mut x = (a.wrapping_mul(73_856_093) ^ b.wrapping_mul(19_349_663)) as u64;
    x ^= x >> 33;
    x = x.wrapping_mul(0xff51_afd7_ed55_8ccd);
    x ^= x >> 33;
    (x % 10_000) as f64 / 10_000.0
}

/// Returns a vector turned by `angle` radians, clockwise on the screen.
fn turn([x, y]: [f64; 2], angle: f64) -> [f64; 2] {
    let (sin, cos) = angle.sin_cos();
    [x * cos - y * sin, x * sin + y * cos]
}

/// Returns a vector with length 1 in the same direction.
fn unit([x, y, z]: [f64; 3]) -> [f64; 3] {
    let length = (x * x + y * y + z * z).sqrt().max(1e-9);
    [x / length, y / length, z / length]
}

/// Returns how high a rounded shape stands over a point, and the direction
/// its surface faces there, or nothing when the point is outside it. The
/// shape is half of an ellipsoid with its center at `center` and radii `rx`,
/// `ry` and `rz`.
fn dome(point: [f64; 2], center: [f64; 2], rx: f64, ry: f64, rz: f64) -> Option<(f64, [f64; 3])> {
    let dx = point[0] - center[0];
    let dy = point[1] - center[1];
    let q = (dx / rx).powi(2) + (dy / ry).powi(2);
    if q >= 1.0 {
        return None;
    }
    let z = rz * (1.0 - q).sqrt();
    Some((z, unit([dx / (rx * rx), dy / (ry * ry), z / (rz * rz)])))
}

/// Returns a color with light from the upper left: the side that faces the
/// light is bright, with a highlight, and the other side is darker.
fn light(base: [f64; 3], normal: [f64; 3]) -> [f64; 3] {
    let to_light = unit([-0.45, -0.62, 0.64]);
    let halfway = unit([to_light[0], to_light[1], to_light[2] + 1.0]);
    let dot = |a: [f64; 3], b: [f64; 3]| (a[0] * b[0] + a[1] * b[1] + a[2] * b[2]).max(0.0);
    let diffuse = dot(normal, to_light);
    let gloss = dot(normal, halfway).powi(28) * 0.5;
    base.map(|channel| (channel * (0.3 + 0.8 * diffuse) + 255.0 * gloss).min(255.0))
}

/// The frog's parts where it sits, with the middle of its body at 0, 0, as
/// centers and radii.
const FROG_BODY: [f64; 3] = [0.9, 0.66, 0.62];
const FROG_EYE: [f64; 2] = [0.4, -0.7];
const FROG_BACK_LEG: [f64; 5] = [0.68, 0.62, 0.28, 0.1, 0.55];
const FROG_FRONT_LEG: [f64; 5] = [0.46, 0.4, 0.16, 0.26, 0.8];

/// The legs as they first bud on the tadpole, round and near the tail, with
/// their centers in parts of the head's radii.
const BACK_BUD: [f64; 5] = [0.8, 0.85, 0.16, 0.12, 0.45];
const FRONT_BUD: [f64; 5] = [0.85, 0.25, 0.13, 0.13, 0.5];

/// The tadpole's head and eyes, the same way. An eye's third number is how
/// far in front of the head's middle it is, which decides where it shows
/// while the tadpole turns.
const TADPOLE_HEAD: [f64; 3] = [0.36, 0.44, 0.45];
const TADPOLE_EYE: [f64; 3] = [0.22, -0.18, 0.3];

/// How far below the head's middle the tadpole's small mouth is, and how far
/// in front.
const TADPOLE_MOUTH: [f64; 2] = [0.16, 0.42];

/// Returns where a point given across, down and toward you from the head's
/// middle shows when the head is turned by `yaw`, and how far toward you it
/// then is. At a quarter turn, what faced you faces right.
fn project([x, y, z]: [f64; 3], yaw: f64) -> ([f64; 2], f64) {
    let (sin, cos) = yaw.sin_cos();
    ([x * cos + z * sin, y], z * cos - x * sin)
}

/// Returns the animal at a point given from the middle of its body, before
/// it is turned to where it heads: the tadpole, the frog, or a stage between
/// them.
fn animal(point: [f64; 2], pose: &Pose) -> Option<Hit> {
    let [x, y] = point;
    let m = pose.morph;
    let rx = lerp(TADPOLE_HEAD[0], FROG_BODY[0], m);
    let ry = lerp(TADPOLE_HEAD[1], FROG_BODY[1], m);
    let rz = lerp(TADPOLE_HEAD[2], FROG_BODY[2], m);
    // Seen from the side, the head is as long as it is deep.
    let (sin, cos) = pose.yaw.sin_cos();
    let wide = (rx * cos).hypot(rz * sin);
    // A point as it would be on the sitting frog, which places the belly and
    // the smile on the body while it still grows.
    let fx = x * FROG_BODY[0] / rx;
    let fy = y * FROG_BODY[1] / ry;
    let skin = lerp3(TADPOLE, SKIN, m);
    let mut best: Option<(f64, Material, [f64; 3], [f64; 3])> = None;
    let mut consider = |found: Option<(f64, [f64; 3])>, material: Material, color: [f64; 3]| {
        if let Some((z, normal)) = found
            && best.is_none_or(|(top, ..)| z > top)
        {
            best = Some((z, material, color, normal));
        }
    };
    // The tadpole's small mouth turns with the head, and stretches into the
    // frog's smile as the head becomes the body. The smile's ends are higher
    // than its middle, since y grows downward.
    let (mouth, _) = project([0.0, TADPOLE_MOUTH[0], TADPOLE_MOUTH[1]], pose.yaw);
    let mouth_x = mouth[0] * FROG_BODY[0] / rx;
    let mouth_y = lerp(mouth[1] * FROG_BODY[1] / TADPOLE_HEAD[1], -0.22, m);
    let half = lerp(0.15, 0.48, m);
    let across = (fx - mouth_x) / half;
    let belly = smooth((m - 0.55) / 0.35);
    let body = if across.abs() < 1.0
        && (fy - (mouth_y - 0.12 * m * across * across)).abs() < lerp(0.09, 0.035, m)
    {
        (Material::Mouth, MOUTH)
    } else if belly > 0.0
        && (fx / (0.5 * belly)).powi(2) + ((fy - 0.24) / (0.32 * belly)).powi(2) < 1.0
    {
        (Material::Belly, lerp3(skin, BELLY, belly))
    } else {
        (Material::Skin, skin)
    };
    consider(dome(point, [0.0, 0.0], wide, ry, rz), body.0, body.1);
    // The tail grows from the back of the head and waves, thinner toward its
    // tip. Seen from the side, it trails behind. Once the tadpole faces you,
    // it points away and down, so that only its end wiggles out below the
    // body, and it shortens and calms until it is gone.
    if pose.tail > 0.0 {
        let length = 0.95 * pose.tail;
        let segments = 18;
        for index in 0..segments {
            let along = (f64::from(index) + 0.5) / f64::from(segments);
            let s = along * length;
            let swing = 0.17 * along.powf(1.2) * (pose.wave - 8.0 * s).sin() * pose.tail;
            // The tail swings across its own direction: up and down from the
            // side, and left and right from the front.
            let spine = [
                swing * cos,
                0.05 + 0.6 * s * cos + swing * sin,
                -0.75 * TADPOLE_HEAD[2] - s,
            ];
            let (center, toward) = project(spine, pose.yaw);
            let radius = (0.13 * (1.0 - along) + 0.03) * pose.tail.sqrt();
            let found = dome(point, center, radius, radius, 0.3 * (1.0 - along) + 0.05)
                .map(|(z, normal)| (z + toward, normal));
            consider(found, Material::Tail, TAIL);
        }
    }
    for side in [-1.0, 1.0] {
        // The legs grow out of the body and move with it as it widens.
        let legs = [
            (BACK_BUD, FROG_BACK_LEG, pose.back),
            (FRONT_BUD, FROG_FRONT_LEG, pose.front),
        ];
        for (bud, leg, grown) in legs {
            if grown > 0.0 {
                let budding = [side * bud[0] * rx, bud[1] * ry];
                let grown_up = [
                    side * leg[0] * rx / FROG_BODY[0],
                    leg[1] * ry / FROG_BODY[1],
                ];
                // A leg starts inside the body and moves out as it pops.
                let out = grown.min(1.0);
                let center = lerp2(budding, grown_up, m).map(|value| value * lerp(0.55, 1.0, out));
                let shape: [f64; 3] = std::array::from_fn(|i| lerp(bud[i + 2], leg[i + 2], m));
                let found = dome(point, center, shape[0] * grown, shape[1] * grown, shape[2]);
                consider(found, Material::Skin, skin);
            }
        }
        // The small black eyes on the sides of the head turn with it, and
        // the one on the far side hides while the tadpole swims. Then they
        // rise and grow into the frog's eyes, with whites around the pupils.
        let ([turned_x, _], toward) = project(
            [side * TADPOLE_EYE[0], TADPOLE_EYE[1], TADPOLE_EYE[2]],
            pose.yaw,
        );
        if toward < 0.0 {
            continue;
        }
        let eye = [
            lerp(turned_x, side * FROG_EYE[0], m),
            lerp(TADPOLE_EYE[1], FROG_EYE[1], m),
        ];
        let radius = lerp(0.1, 0.25, m);
        let ex = x - eye[0];
        let ey = y - eye[1];
        let ball = (ex * ex + ey * ey).sqrt() < radius * lerp(1.0, 0.68, m);
        let lid = ey < radius * (-1.0 + 2.0 * pose.blink);
        let pupil = (ex / (radius * lerp(0.6, 0.4, m))).powi(2)
            + (ey / (radius * lerp(0.6, 0.3, m))).powi(2)
            < 1.0;
        let shine =
            (ex + 0.2 * radius).powi(2) + (ey + 0.2 * radius).powi(2) < (0.16 * radius).powi(2);
        let (material, color) = if !ball || lid {
            (Material::Skin, skin)
        } else if shine {
            (Material::Shine, SHINE)
        } else if pupil {
            (Material::Pupil, PUPIL)
        } else {
            (Material::EyeWhite, EYE_WHITE)
        };
        consider(
            dome(point, eye, radius, radius, lerp(0.5, 0.8, m)),
            material,
            color,
        );
    }
    best.map(|(_, material, color, normal)| {
        let lit = if material == Material::Shine {
            color
        } else {
            light(color, normal)
        };
        (material, lit)
    })
}

/// Returns what shows at a point of the stage, with `fade` the point's own
/// random number, which lets the tadpole appear dot by dot.
fn sample(pose: &Pose, point: [f64; 2], fade: f64) -> Option<Hit> {
    if fade >= pose.appear {
        return None;
    }
    // The frog hops and squashes around the middle of its feet.
    let width = 1.0 + pose.squash;
    let height = 1.0 - pose.squash;
    let point = [
        (point[0] - FEET[0]) / width + FEET[0],
        (point[1] - pose.lift - FEET[1]) / height + FEET[1],
    ];
    let from_body = [point[0] - pose.center[0], point[1] - pose.center[1]];
    let unturned = turn(from_body, -pose.tilt);
    animal(unturned, pose)
}

/// Returns the frame `t` seconds into the animation: `COLUMNS` cells for each
/// of the `ROWS` rows, row by row.
pub fn frame(t: f64) -> Vec<Cell> {
    // The bounce only fades, so the last frame is the frame at the end.
    let pose = pose(t.min(LENGTH));
    let columns = usize::from(COLUMNS);
    let rows = usize::from(ROWS);
    let dot_columns = columns * 2;
    let dot_rows = rows * 4;
    // One unit is half the stage's height, and dots are about square.
    let scale = dot_rows as f64 / 2.0;
    let mut cells = Vec::with_capacity(columns * rows);
    for row in 0..rows {
        for column in 0..columns {
            let mut hits: [Option<Hit>; 8] = [None; 8];
            for (index, hit) in hits.iter_mut().enumerate() {
                let dx = column * 2 + index % 2;
                let dy = row * 4 + index / 2;
                let point = [
                    (dx as f64 + 0.5 - dot_columns as f64 / 2.0) / scale,
                    (dy as f64 + 0.5 - dot_rows as f64 / 2.0) / scale,
                ];
                *hit = sample(&pose, point, noise(dx as i64, dy as i64 + 1_000));
            }
            cells.push(cell(&hits));
        }
    }
    cells
}

/// Returns the cell for the eight dots of one character. A cell that is only
/// partly covered shows its dots over the terminal's own background. A cell
/// that is covered fully gets the color of its main material behind the
/// dots, and the dots show the other materials in it, so that small parts,
/// such as a pupil, keep their shape.
fn cell(hits: &[Option<Hit>; 8]) -> Cell {
    let average = |pick: &dyn Fn(Material) -> bool| -> Option<[u8; 3]> {
        let chosen: Vec<[f64; 3]> = hits
            .iter()
            .flatten()
            .filter(|(material, _)| pick(*material))
            .map(|(_, color)| *color)
            .collect();
        if chosen.is_empty() {
            return None;
        }
        let count = chosen.len() as f64;
        Some(std::array::from_fn(|channel| {
            (chosen.iter().map(|color| color[channel]).sum::<f64>() / count).round() as u8
        }))
    };
    let mask = |pick: &dyn Fn(Material) -> bool| -> u8 {
        hits.iter()
            .zip(DOT_BITS)
            .filter(|(hit, _)| hit.is_some_and(|(material, _)| pick(material)))
            .fold(0, |dots, (_, bit)| dots | bit)
    };
    let covered = hits.iter().filter(|hit| hit.is_some()).count();
    if covered == 0 {
        return Cell::default();
    }
    if covered < hits.len() {
        return Cell {
            dots: mask(&|_| true),
            fg: average(&|_| true).unwrap_or_default(),
            bg: None,
        };
    }
    let mut counts: Vec<(Material, usize)> = Vec::new();
    for (material, _) in hits.iter().flatten() {
        match counts.iter_mut().find(|(seen, _)| seen == material) {
            Some((_, count)) => *count += 1,
            None => counts.push((*material, 1)),
        }
    }
    let main = counts
        .iter()
        .max_by_key(|(_, count)| *count)
        .map(|(material, _)| *material)
        .expect("a covered cell has a material");
    let behind = average(&|material| material == main).unwrap_or_default();
    match average(&|material| material != main) {
        Some(front) => Cell {
            dots: mask(&|material| material != main),
            fg: front,
            bg: Some(behind),
        },
        // One material: the dots are a little darker than the color
        // behind them, which keeps the dotted look of the edges.
        None => Cell {
            dots: 0xff,
            fg: behind.map(|channel| (f64::from(channel) * 0.88) as u8),
            bg: Some(behind),
        },
    }
}

/// Returns the closest of the 256 colors that terminals without full color
/// support, such as macOS Terminal, can show.
pub fn to_256(rgb: [u8; 3]) -> u8 {
    let level = |channel: u8| -> u8 {
        if channel < 48 {
            0
        } else if channel < 115 {
            1
        } else {
            (channel - 35) / 40
        }
    };
    let [r, g, b] = rgb.map(level);
    16 + 36 * r + 6 * g + b
}

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

    fn green(cell: &Cell) -> bool {
        let [r, g, b] = cell.bg.unwrap_or(cell.fg);
        cell.dots != 0 && g > r.saturating_add(40) && g > b.saturating_add(40)
    }

    #[test]
    fn every_frame_fills_the_stage() {
        for step in 0..=70 {
            let t = f64::from(step) / 20.0;
            assert_eq!(frame(t).len(), usize::from(COLUMNS) * usize::from(ROWS));
        }
    }

    #[test]
    fn the_tadpole_comes_first_and_the_frog_last() {
        assert!(frame(0.0).iter().all(|cell| cell.dots == 0));
        let tadpole = frame(0.8);
        assert!(tadpole.iter().filter(|cell| cell.dots != 0).count() > 10);
        assert_eq!(tadpole.iter().filter(|cell| green(cell)).count(), 0);
        let frog = frame(LENGTH);
        assert!(frog.iter().filter(|cell| green(cell)).count() > 60);
    }

    #[test]
    fn the_tadpole_swims_in_from_the_side_and_turns_to_face_you() {
        assert!((pose(0.3).yaw - PI / 2.0).abs() < 1e-9);
        assert!(pose(0.3).center[0] < -0.5);
        assert_eq!(pose(LENGTH).yaw, 0.0);
        assert_eq!(pose(LENGTH).center, BODY);
        assert_eq!(pose(LENGTH).tail, 0.0);
    }

    #[test]
    fn a_turned_head_shows_its_front_on_the_right() {
        let ([x, y], toward) = project([0.0, 0.1, 0.4], PI / 2.0);
        assert!((x - 0.4).abs() < 1e-9 && y == 0.1 && toward.abs() < 1e-9);
        let (_, near_side) = project([-0.2, 0.0, 0.3], PI / 2.0);
        assert!(near_side > 0.0);
        let (_, far_side) = project([0.2, 0.0, 0.3], PI / 2.0);
        assert!(far_side < 0.0);
    }

    #[test]
    fn the_back_legs_pop_out_before_the_front_legs() {
        let back_out = (0..80)
            .map(|step| f64::from(step) / 20.0)
            .find(|t| pose(*t).back > 0.0);
        let front_out = (0..80)
            .map(|step| f64::from(step) / 20.0)
            .find(|t| pose(*t).front > 0.0);
        assert!(back_out < front_out);
        assert!((pose(LENGTH).back - 1.0).abs() < 1e-9);
    }

    #[test]
    fn a_frame_is_the_same_every_time() {
        assert_eq!(frame(1.7), frame(1.7));
    }

    #[test]
    fn the_last_frame_stays_after_the_animation() {
        assert_eq!(frame(LENGTH), frame(LENGTH + 5.0));
    }

    #[test]
    fn cells_show_braille_characters() {
        let cell = Cell {
            dots: 0xff,
            ..Cell::default()
        };
        assert_eq!(cell.symbol(), '⣿');
        assert_eq!(Cell::default().symbol(), '\u{2800}');
    }

    #[test]
    fn colors_map_to_the_256_color_cube() {
        assert_eq!(to_256([0, 0, 0]), 16);
        assert_eq!(to_256([255, 255, 255]), 231);
        assert_eq!(to_256([255, 0, 0]), 196);
    }
}