printobserver-panels 0.20.0

Camera calibration, drift and alignment checks, and the check image's panels, for printobserver.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
//! The image a look at the printer is shown: the whole camera frame, and
//! under it a close-up of the build sheet's edges and clips.
//!
//! Before a print starts, whether the bed is clear is judged on this image. A
//! purge strand left along the sheet's edge beside a clip is a few pixels wide
//! in the whole frame, so the edges are shown again, cut from the frame at its
//! full resolution and enlarged [`MAGNIFICATION`] times over the whole frame's
//! scale.
//!
//! 1. Panel 1 is the whole frame, scaled to fit [`WHOLE_FRAME_WIDTH`] by
//!    [`crate::WHOLE_FRAME_HEIGHT`] exactly as [`crate::whole_frame`] scales
//!    it, nothing drawn.
//! 2. Panel 2 is each edge of the sheet unrolled into a strip: the band
//!    [`OUTSIDE_PX`] outside the edge to [`INSIDE_PX`] inside it, turned so the
//!    outside is up and the sheet down, never mirrored, labelled by which way
//!    the edge faces in the frame. The strips run on in rows of the whole
//!    frame's width.
//!
//! The sheet is located from the camera's calibration where one is given and
//! fits the frame ([`LocatedBy::Calibration`]): the frame is its size and
//! stream, its landmarks show no move, and a committed sheet's outline is fitted
//! to the frame's edges at some bed height. Otherwise it is located in the frame
//! itself ([`LocatedBy::Frame`]): the largest smooth, lit region of the frame,
//! taken as its convex hull, so a strand lying along the edge falls inside the
//! hull rather than bending it. A frame in which neither finds a sheet has no
//! close-up, and its look is shown the whole frame alone.

use image::imageops::FilterType;
use image::{Rgb, RgbImage};
use imageproc::drawing::draw_filled_rect_mut;
use imageproc::rect::Rect;

use crate::calibration::CameraCalibration;
use crate::compose::decode;
use crate::error::ComposeError;
use crate::sheet::{blurred, calibrated_outline};
use crate::text::draw_text;
use crate::whole_frame::{WHOLE_FRAME_WIDTH, scaled_size};

/// How many times larger the close-up shows the frame than panel 1 does.
pub const MAGNIFICATION: f64 = 2.0;

/// How far outside the located edge each strip reaches, in pixels of a frame
/// [`WHOLE_FRAME_WIDTH`] wide, scaled with the frame's width: far enough for a
/// clip standing on the edge.
pub const OUTSIDE_PX: f64 = 36.0;

/// How far inside the located edge each strip reaches, in the same pixels:
/// far enough for a strand lying along the edge, and for the edge itself where
/// the frame's own location of it falls short of the rim.
pub const INSIDE_PX: f64 = 36.0;

/// The tallest the image may be: the long edge the supervising model takes an
/// image at without scaling it down.
pub const MAX_HEIGHT: u32 = 2576;

/// The band each panel's label is written in.
const BAND_HEIGHT: u32 = 32;

/// The band above each row of strips their labels are written in.
const ROW_LABEL_HEIGHT: u32 = 22;

/// The space between two strips in one row, and between two rows.
const GAP_PX: u32 = 12;

/// The narrowest piece a strip is begun with in a row: room for its label.
const MIN_PIECE_PX: u32 = 160;

/// The width the frame is located in when located in the frame itself.
const WORK_WIDTH: u32 = 320;

/// The blur the located-in-frame grey is read through, in working pixels.
const WORK_BLUR_SIGMA: f64 = 2.0;

/// The gradient, in grey levels per working pixel, below which a working pixel
/// is smooth: the sheet's own shading and a textured sheet's grain stay under
/// it, and its rim does not.
const SMOOTH_BELOW: f64 = 4.0;

/// The dimmest a region may be on average and still be a sheet: the frame's
/// black surroundings are smooth too.
const LIT_FROM: f64 = 60.0;

/// The least share of the frame a sheet located in the frame covers.
const MIN_SHARE: f64 = 0.05;

/// The least share of its hull the region must fill: a region far from
/// convex is not a sheet, and its hull would close over what is not.
const MIN_FILL: f64 = 0.75;

/// How far inside the frame's border, in pixels of a frame
/// [`WHOLE_FRAME_WIDTH`] wide, an edge must lie to be shown: a hull running
/// along the border is the frame's edge, not the sheet's.
const BORDER_PX: f64 = 8.0;

/// The shortest run of edge shown, in the same pixels.
const MIN_RUN_PX: f64 = 40.0;

/// How far along the edge either side its direction is read over, in samples.
const TANGENT_REACH: usize = 12;

/// The most corners the hull is reduced to before its four are chosen.
const MAX_CORNER_CANDIDATES: usize = 40;

/// The JPEG quality the image is written at.
const QUALITY: u8 = 90;

/// The label bands' background.
const BAND: Rgb<u8> = Rgb([24, 24, 24]);

/// The label text.
const TEXT: Rgb<u8> = Rgb([235, 235, 235]);

/// What a strip shows where it reaches outside the frame.
const OFF_FRAME: Rgb<u8> = Rgb([32, 32, 32]);

/// How the sheet was located.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LocatedBy {
    /// From the camera's calibration, which fits the frame.
    Calibration,
    /// From the frame itself.
    Frame,
}

/// What the image is made from.
#[derive(Debug, Clone, Copy)]
pub struct SheetEdgesInputs<'a> {
    /// The frame.
    pub frame_jpeg: &'a [u8],
    /// The camera's calibration and the snapshot URL the frame came from,
    /// when a calibration is configured.
    pub calibration: Option<(&'a CameraCalibration, &'a str)>,
}

/// One edge's strip: its centre line in frame pixels, one sample a pixel apart,
/// and the outward normal at each.
#[derive(Debug, Clone, PartialEq)]
pub struct EdgeStrip {
    /// Which way the edge faces in the frame, as its label says.
    pub name: &'static str,
    /// The located edge, in frame pixels.
    pub points: Vec<[f64; 2]>,
    /// The outward normal at each point, unit length.
    pub normals: Vec<[f64; 2]>,
}

/// One piece of a strip where the image places it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Piece {
    /// The strip, an index into [`SheetEdges::strips`].
    pub strip: usize,
    /// How far along its strip the piece starts, in image pixels.
    pub from_px: u32,
    /// Where it is in the image: `[x, y, width, height]`.
    pub rect: [u32; 4],
}

/// The image, and where each of its close-up's pixels comes from.
#[derive(Debug, Clone, PartialEq)]
pub struct SheetEdges {
    /// The JPEG.
    pub jpeg: Vec<u8>,
    /// Its width: panel 1's.
    pub width: u32,
    /// Its height.
    pub height: u32,
    /// How the sheet was located.
    pub located_by: LocatedBy,
    /// Panel 1's pixels per frame pixel.
    pub whole_scale: f64,
    /// The close-up's pixels per frame pixel: [`MAGNIFICATION`] times
    /// `whole_scale`.
    pub close_up_scale: f64,
    /// The located sheet's outline, a convex polygon in frame pixels.
    pub outline: Vec<[f64; 2]>,
    /// Every edge shown.
    pub strips: Vec<EdgeStrip>,
    /// Where each piece of each strip is.
    pub pieces: Vec<Piece>,
    /// How far outside the edge each strip reaches, in frame pixels.
    pub outside_px: f64,
}

impl SheetEdges {
    /// The frame point one pixel of the close-up shows; nothing for a pixel
    /// outside every strip.
    #[must_use]
    pub fn source_point(&self, at: [u32; 2]) -> Option<[f64; 2]> {
        let piece = self.pieces.iter().find(|piece| {
            let [x, y, w, h] = piece.rect;
            (x..x + w).contains(&at[0]) && (y..y + h).contains(&at[1])
        })?;
        let strip = &self.strips[piece.strip];
        let along = f64::from(at[0] - piece.rect[0] + piece.from_px) + 0.5;
        let down = f64::from(at[1] - piece.rect[1]) + 0.5;
        Some(strip_point(
            strip,
            along / self.close_up_scale,
            self.outside_px - down / self.close_up_scale,
        ))
    }
}

/// The whole frame and the close-up of its sheet's edges, as one image.
///
/// # Errors
///
/// [`ComposeError::Undecodable`] for a frame that is no JPEG, and
/// [`ComposeError::Encode`] when the image cannot be encoded. A frame on which
/// no sheet is located is no error: it is answered as nothing.
pub fn sheet_edges(inputs: &SheetEdgesInputs<'_>) -> Result<Option<SheetEdges>, ComposeError> {
    let frame = decode(inputs.frame_jpeg)?;
    let calibrated = inputs
        .calibration
        .and_then(|(calibration, url)| calibrated_outline(&frame, url, calibration));
    let (points, located_by) = match calibrated {
        Some(points) => (points, LocatedBy::Calibration),
        None => match outline_in_frame(&frame) {
            Some(points) => (points, LocatedBy::Frame),
            None => return Ok(None),
        },
    };
    let outline = clockwise(convex_hull(&points));
    if outline.len() < 4 {
        return Ok(None);
    }
    let size = [frame.width(), frame.height()];
    let per_width = f64::from(size[0]) / f64::from(WHOLE_FRAME_WIDTH);
    let strips = strips_of(&outline, size, per_width);
    if strips.is_empty() {
        return Ok(None);
    }
    let (whole_width, whole_height) = scaled_size(size[0], size[1]);
    let whole_scale = f64::from(whole_width) / f64::from(size[0]);
    let close_up_scale = MAGNIFICATION * whole_scale;
    let outside_px = OUTSIDE_PX * per_width;
    let strip_height = pixels((OUTSIDE_PX + INSIDE_PX) * per_width * close_up_scale);
    let top = 2 * BAND_HEIGHT + whole_height;
    let pieces = laid_out(&strips, close_up_scale, whole_width, top, strip_height);
    let height = pieces
        .iter()
        .map(|piece| piece.rect[1] + piece.rect[3])
        .max()
        .unwrap_or(top)
        + GAP_PX;
    let mut edges = SheetEdges {
        jpeg: Vec::new(),
        width: whole_width,
        height,
        located_by,
        whole_scale,
        close_up_scale,
        outline,
        strips,
        pieces,
        outside_px,
    };
    edges.jpeg = drawn(&frame, &edges, whole_height)?;
    Ok(Some(edges))
}

/// The image itself.
fn drawn(frame: &RgbImage, edges: &SheetEdges, whole_height: u32) -> Result<Vec<u8>, ComposeError> {
    let mut image = RgbImage::from_pixel(edges.width, edges.height, BAND);
    let whole = if (edges.width, whole_height) == frame.dimensions() {
        frame.clone()
    } else {
        image::imageops::resize(frame, edges.width, whole_height, FilterType::Triangle)
    };
    image::imageops::replace(&mut image, &whole, 0, i64::from(BAND_HEIGHT));
    draw_text(
        &mut image,
        TEXT,
        8,
        7,
        18.0,
        "1 THE WHOLE FRAME, nothing drawn",
    );
    let second = BAND_HEIGHT + whole_height;
    draw_text(
        &mut image,
        TEXT,
        8,
        signed(second + 7),
        18.0,
        "2 CLOSE-UP x2 of the sheet's edges and clips: each edge unrolled, outside up, sheet down",
    );
    for piece in &edges.pieces {
        let [x, y, w, h] = piece.rect;
        let strip = &edges.strips[piece.strip];
        let label = if piece.from_px == 0 {
            format!("{} edge", strip.name)
        } else {
            format!("{} edge, cont.", strip.name)
        };
        draw_text(
            &mut image,
            TEXT,
            signed(x + 2),
            signed(y - ROW_LABEL_HEIGHT + 3),
            15.0,
            &label,
        );
        draw_filled_rect_mut(
            &mut image,
            Rect::at(signed(x), signed(y)).of_size(w, h),
            OFF_FRAME,
        );
        for v in 0..h {
            for u in 0..w {
                if let Some(point) = edges.source_point([x + u, y + v])
                    && let Some(colour) = sampled(frame, point)
                {
                    image.put_pixel(x + u, y + v, colour);
                }
            }
        }
    }
    let mut jpeg = Vec::new();
    image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, QUALITY)
        .encode_image(&image)
        .map_err(|error| ComposeError::Encode {
            detail: error.to_string(),
        })?;
    Ok(jpeg)
}

/// Where each strip's pieces go: row after row of the image's width, a strip
/// begun only where its label has room, and continued in the next row.
fn laid_out(
    strips: &[EdgeStrip],
    scale: f64,
    width: u32,
    top: u32,
    strip_height: u32,
) -> Vec<Piece> {
    let row_height = ROW_LABEL_HEIGHT + strip_height + GAP_PX;
    let mut pieces = Vec::new();
    let (mut row, mut x) = (0_u32, 0_u32);
    for (index, strip) in strips.iter().enumerate() {
        let length =
            pixels(f64::from(u32::try_from(strip.points.len()).unwrap_or(u32::MAX)) * scale);
        let mut from = 0;
        while from < length {
            if width.saturating_sub(x) < MIN_PIECE_PX.min(length - from) {
                row += 1;
                x = 0;
            }
            let taken = (width - x).min(length - from);
            pieces.push(Piece {
                strip: index,
                from_px: from,
                rect: [
                    x,
                    top + row * row_height + ROW_LABEL_HEIGHT,
                    taken,
                    strip_height,
                ],
            });
            from += taken;
            x += taken + GAP_PX;
        }
    }
    pieces
}

/// The point `outward` frame pixels outward of the strip's edge, `along` frame
/// pixels along it.
fn strip_point(strip: &EdgeStrip, along: f64, outward: f64) -> [f64; 2] {
    let last = strip.points.len().saturating_sub(1);
    let clamped = along.clamp(0.0, f64::from(u32::try_from(last).unwrap_or(0)));
    let index = index_of(clamped).min(last);
    let next = (index + 1).min(last);
    let t = clamped - f64::from(u32::try_from(index).unwrap_or(0));
    let mix = |a: [f64; 2], b: [f64; 2]| [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];
    let point = mix(strip.points[index], strip.points[next]);
    let normal = mix(strip.normals[index], strip.normals[next]);
    let length = normal[0].hypot(normal[1]).max(1e-9);
    [
        point[0] + outward * normal[0] / length,
        point[1] + outward * normal[1] / length,
    ]
}

/// The frame's colour at a point, bilinearly; nothing outside it.
fn sampled(frame: &RgbImage, [x, y]: [f64; 2]) -> Option<Rgb<u8>> {
    let (width, height) = (f64::from(frame.width()), f64::from(frame.height()));
    if !(0.0..=width - 1.0).contains(&x) || !(0.0..=height - 1.0).contains(&y) {
        return None;
    }
    let (x0, y0) = (index_of(x.floor()), index_of(y.floor()));
    let (fx, fy) = (x - x.floor(), y - y.floor());
    let last = |size: u32| usize::try_from(size - 1).unwrap_or(0);
    let (x1, y1) = (
        (x0 + 1).min(last(frame.width())),
        (y0 + 1).min(last(frame.height())),
    );
    let at = |x: usize, y: usize| {
        frame.get_pixel(u32::try_from(x).unwrap_or(0), u32::try_from(y).unwrap_or(0))
    };
    let mut out = [0_u8; 3];
    for (channel, value) in out.iter_mut().enumerate() {
        let top = f64::from(at(x0, y0)[channel]) * (1.0 - fx) + f64::from(at(x1, y0)[channel]) * fx;
        let bottom =
            f64::from(at(x0, y1)[channel]) * (1.0 - fx) + f64::from(at(x1, y1)[channel]) * fx;
        *value = channel_of(top * (1.0 - fy) + bottom * fy);
    }
    Some(Rgb(out))
}

/// The sheet's region in the frame itself, as the points of its outline in
/// frame pixels: the largest smooth, lit region of a working copy, weighed by
/// its area and the square of its mean grey. Nothing when no region is large,
/// lit and convex enough to be a sheet.
fn outline_in_frame(frame: &RgbImage) -> Option<Vec<[f64; 2]>> {
    let scale = f64::from(frame.width()) / f64::from(WORK_WIDTH);
    let work_height = pixels(f64::from(frame.height()) / scale).max(1);
    let work = image::imageops::grayscale(&image::imageops::resize(
        frame,
        WORK_WIDTH,
        work_height,
        FilterType::Triangle,
    ));
    let (width, height) = (
        usize::try_from(WORK_WIDTH).ok()?,
        usize::try_from(work.height()).ok()?,
    );
    let raw: Vec<f64> = work
        .as_raw()
        .iter()
        .map(|value| f64::from(*value))
        .collect();
    let grey = blurred(&raw, width, height, WORK_BLUR_SIGMA);
    let at = |x: usize, y: usize| grey[y * width + x];
    let smooth: Vec<bool> = (0..width * height)
        .map(|k| {
            let (x, y) = (k % width, k / width);
            let (left, right) = (x.saturating_sub(1), (x + 1).min(width - 1));
            let (up, down) = (y.saturating_sub(1), (y + 1).min(height - 1));
            let gx = ((at(right, up) - at(left, up))
                + 2.0 * (at(right, y) - at(left, y))
                + (at(right, down) - at(left, down)))
                / 8.0;
            let gy = ((at(left, down) - at(left, up))
                + 2.0 * (at(x, down) - at(x, up))
                + (at(right, down) - at(right, up)))
                / 8.0;
            gx.hypot(gy) < SMOOTH_BELOW
        })
        .collect();
    let (labels, regions) = regions_of(&smooth, &grey, width, height);
    let total = f64::from(u32::try_from(width * height).ok()?);
    let (label, region) = regions
        .iter()
        .enumerate()
        .filter(|(_, region)| region.share(total) >= MIN_SHARE && region.mean() >= LIT_FROM)
        .max_by(|a, b| a.1.weight().total_cmp(&b.1.weight()))?;
    let centres: Vec<[f64; 2]> = labels
        .iter()
        .enumerate()
        .filter(|(_, of)| **of == label)
        .map(|(k, _)| [coordinate(k % width) + 0.5, coordinate(k / width) + 0.5])
        .collect();
    let hull = convex_hull(&centres);
    if region.area / polygon_area(&hull).abs().max(1.0) < MIN_FILL {
        return None;
    }
    Some(hull.iter().map(|[x, y]| [x * scale, y * scale]).collect())
}

/// One connected smooth region of the working copy.
#[derive(Debug, Clone, Copy, Default)]
struct Region {
    /// Its pixels.
    area: f64,
    /// The sum of their grey.
    grey: f64,
}

impl Region {
    /// Its mean grey.
    fn mean(self) -> f64 {
        self.grey / self.area.max(1.0)
    }

    /// Its share of `total` pixels.
    fn share(self, total: f64) -> f64 {
        self.area / total
    }

    /// What the sheet is chosen by: its area, weighed by the square of its
    /// mean grey, so a large dim wall loses to a lit sheet.
    fn weight(self) -> f64 {
        self.area * self.mean() * self.mean()
    }
}

/// The four-connected regions of the `smooth` pixels: each pixel's region, and
/// each region.
fn regions_of(
    smooth: &[bool],
    grey: &[f64],
    width: usize,
    height: usize,
) -> (Vec<usize>, Vec<Region>) {
    let mut labels = vec![usize::MAX; smooth.len()];
    let mut regions = Vec::new();
    for start in 0..smooth.len() {
        if !smooth[start] || labels[start] != usize::MAX {
            continue;
        }
        let label = regions.len();
        let mut region = Region::default();
        let mut stack = vec![start];
        labels[start] = label;
        while let Some(at) = stack.pop() {
            region.area += 1.0;
            region.grey += grey[at];
            let (x, y) = (at % width, at / width);
            let neighbours = [
                (x > 0).then(|| at - 1),
                (x + 1 < width).then(|| at + 1),
                (y > 0).then(|| at - width),
                (y + 1 < height).then(|| at + width),
            ];
            for next in neighbours.into_iter().flatten() {
                if smooth[next] && labels[next] == usize::MAX {
                    labels[next] = label;
                    stack.push(next);
                }
            }
        }
        regions.push(region);
    }
    (labels, regions)
}

/// The convex hull of a set of points, by the monotone chain.
fn convex_hull(points: &[[f64; 2]]) -> Vec<[f64; 2]> {
    let mut sorted = points.to_vec();
    sorted.sort_by(|a, b| a[0].total_cmp(&b[0]).then(a[1].total_cmp(&b[1])));
    sorted.dedup();
    if sorted.len() < 3 {
        return sorted;
    }
    let cross = |o: [f64; 2], a: [f64; 2], b: [f64; 2]| {
        (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
    };
    let mut hull: Vec<[f64; 2]> = Vec::with_capacity(sorted.len() * 2);
    for pass in [sorted.clone(), sorted.iter().rev().copied().collect()] {
        let floor = hull.len();
        for point in pass {
            while hull.len() >= floor + 2
                && cross(hull[hull.len() - 2], hull[hull.len() - 1], point) <= 0.0
            {
                hull.pop();
            }
            hull.push(point);
        }
        hull.pop();
    }
    hull
}

/// The polygon's signed area by the shoelace formula, positive
/// for a polygon running clockwise on the screen, where `y` grows downward.
fn polygon_area(polygon: &[[f64; 2]]) -> f64 {
    let n = polygon.len();
    (0..n)
        .map(|i| {
            let (a, b) = (polygon[i], polygon[(i + 1) % n]);
            a[0] * b[1] - b[0] * a[1]
        })
        .sum::<f64>()
        / 2.0
}

/// The polygon running clockwise on the screen, so the outward normal of an
/// edge running along `t` is `(t.y, -t.x)`.
fn clockwise(mut polygon: Vec<[f64; 2]>) -> Vec<[f64; 2]> {
    if polygon_area(&polygon) < 0.0 {
        polygon.reverse();
    }
    polygon
}

/// The indices of the hull's four corners, in order: the four of its vertices
/// spanning the largest quadrilateral, chosen among the vertices that turn it
/// most.
fn corners(hull: &[[f64; 2]]) -> [usize; 4] {
    let mut kept: Vec<usize> = (0..hull.len()).collect();
    // The vertex whose removal changes the outline least goes first.
    while kept.len() > MAX_CORNER_CANDIDATES {
        let n = kept.len();
        let least = (0..n)
            .min_by(|&a, &b| {
                let area = |i: usize| {
                    polygon_area(&[
                        hull[kept[(i + n - 1) % n]],
                        hull[kept[i]],
                        hull[kept[(i + 1) % n]],
                    ])
                    .abs()
                };
                area(a).total_cmp(&area(b))
            })
            .unwrap_or(0);
        kept.remove(least);
    }
    let n = kept.len();
    let mut best = ([0, 1, 2, 3], f64::MIN);
    for a in 0..n {
        for b in a + 1..n {
            for c in b + 1..n {
                for d in c + 1..n {
                    let area =
                        polygon_area(&[hull[kept[a]], hull[kept[b]], hull[kept[c]], hull[kept[d]]]);
                    if area > best.1 {
                        best = ([kept[a], kept[b], kept[c], kept[d]], area);
                    }
                }
            }
        }
    }
    best.0
}

/// Every edge of the outline shown, a strip each: the hull between two corners
/// resampled a pixel apart and carried past each corner by the strip's reach
/// outside, the runs of it lying inside the frame's border, each long enough.
fn strips_of(outline: &[[f64; 2]], size: [u32; 2], per_width: f64) -> Vec<EdgeStrip> {
    let corners = corners(outline);
    let n = outline.len();
    let margin = BORDER_PX * per_width;
    let (width, height) = (f64::from(size[0]), f64::from(size[1]));
    let inside = |[x, y]: [f64; 2]| {
        x >= margin && y >= margin && x <= width - margin && y <= height - margin
    };
    let mut strips = Vec::new();
    for side in 0..4 {
        let (from, to) = (corners[side], corners[(side + 1) % 4]);
        let mut chain = vec![outline[from]];
        let mut at = from;
        while at != to {
            at = (at + 1) % n;
            chain.push(outline[at]);
        }
        let points = extended(&resampled(&chain), OUTSIDE_PX * per_width);
        let normals = normals_of(&points);
        let mut run: Vec<usize> = Vec::new();
        for index in 0..=points.len() {
            if index < points.len() && inside(points[index]) {
                run.push(index);
                continue;
            }
            if f64::from(u32::try_from(run.len()).unwrap_or(0)) >= MIN_RUN_PX * per_width {
                let (points, normals): (Vec<_>, Vec<_>) =
                    run.iter().map(|&k| (points[k], normals[k])).unzip();
                let name = facing(&normals);
                strips.push(EdgeStrip {
                    name,
                    points,
                    normals,
                });
            }
            run.clear();
        }
    }
    strips
}

/// A polyline resampled at one pixel along its length.
fn resampled(chain: &[[f64; 2]]) -> Vec<[f64; 2]> {
    let mut out = vec![chain[0]];
    let mut carried = 0.0;
    for pair in chain.windows(2) {
        let (a, b) = (pair[0], pair[1]);
        let length = (b[0] - a[0]).hypot(b[1] - a[1]);
        let mut t = 1.0 - carried;
        while t <= length {
            let f = t / length;
            out.push([a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f]);
            t += 1.0;
        }
        carried = length - (t - 1.0);
    }
    out
}

/// A resampled polyline carried `reach` pixels on past each end, along its end
/// direction, so a corner and what stands at it are in both its strips.
fn extended(points: &[[f64; 2]], reach: f64) -> Vec<[f64; 2]> {
    if points.len() < 2 {
        return points.to_vec();
    }
    let unit = |a: [f64; 2], b: [f64; 2]| {
        let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
        let length = dx.hypot(dy).max(1e-9);
        [dx / length, dy / length]
    };
    let steps = index_of(reach.round());
    let reach_back = TANGENT_REACH.min(points.len() - 1);
    let first = points[0];
    let back = unit(points[reach_back], first);
    let last = points[points.len() - 1];
    let on = unit(points[points.len() - 1 - reach_back], last);
    let mut out: Vec<[f64; 2]> = (1..=steps)
        .rev()
        .map(|k| {
            let k = coordinate(k);
            [first[0] + back[0] * k, first[1] + back[1] * k]
        })
        .collect();
    out.extend_from_slice(points);
    out.extend((1..=steps).map(|k| {
        let k = coordinate(k);
        [last[0] + on[0] * k, last[1] + on[1] * k]
    }));
    out
}

/// The outward normal at each point of a polyline running clockwise on the
/// screen, read over [`TANGENT_REACH`] samples either side.
fn normals_of(points: &[[f64; 2]]) -> Vec<[f64; 2]> {
    let last = points.len().saturating_sub(1);
    (0..points.len())
        .map(|k| {
            let (a, b) = (
                points[k.saturating_sub(TANGENT_REACH)],
                points[(k + TANGENT_REACH).min(last)],
            );
            let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
            let length = dx.hypot(dy).max(1e-9);
            [dy / length, -dx / length]
        })
        .collect()
}

/// Which way an edge with these outward normals faces in the frame.
fn facing(normals: &[[f64; 2]]) -> &'static str {
    let sum = normals
        .iter()
        .fold([0.0, 0.0], |sum, n| [sum[0] + n[0], sum[1] + n[1]]);
    // Up the screen is a positive angle.
    let degrees = (-sum[1]).atan2(sum[0]).to_degrees();
    let names = [
        "right",
        "upper-right",
        "top",
        "upper-left",
        "left",
        "lower-left",
        "bottom",
        "lower-right",
    ];
    let sector = ((degrees + 360.0 + 22.5) / 45.0).floor();
    names[index_of(sector) % names.len()]
}

/// A non-negative whole number of pixels, rounded.
fn pixels(value: f64) -> u32 {
    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "clamped to the range of a pixel count just above"
    )]
    let count = value.round().clamp(0.0, f64::from(u32::MAX)) as u32;
    count
}

/// A non-negative whole number as an index, rounded down.
fn index_of(value: f64) -> usize {
    usize::try_from(pixels(value.floor())).unwrap_or(0)
}

/// An index as a coordinate.
fn coordinate(index: usize) -> f64 {
    f64::from(u32::try_from(index).unwrap_or(u32::MAX))
}

/// A colour channel, rounded and clamped.
fn channel_of(value: f64) -> u8 {
    u8::try_from(pixels(value).min(255)).unwrap_or(u8::MAX)
}

/// A pixel position as a drawing coordinate.
fn signed(value: u32) -> i32 {
    i32::try_from(value).unwrap_or(i32::MAX)
}

#[cfg(test)]
mod tests {
    use super::{clockwise, convex_hull, corners, facing, polygon_area, resampled};

    #[test]
    fn a_square_hull_runs_clockwise_on_the_screen_with_its_four_corners() {
        let mut points = vec![
            [0.0, 0.0],
            [10.0, 0.0],
            [10.0, 10.0],
            [0.0, 10.0],
            [5.0, 5.0],
        ];
        for k in 1..10 {
            points.push([f64::from(k), 0.0]);
        }
        let hull = clockwise(convex_hull(&points));
        assert_eq!(hull.len(), 4, "{hull:?}");
        assert!(polygon_area(&hull) > 0.0);
        let mut found = corners(&hull).to_vec();
        found.sort_unstable();
        assert_eq!(found, vec![0, 1, 2, 3]);
    }

    #[test]
    fn a_polyline_is_resampled_a_pixel_apart() {
        let points = resampled(&[[0.0, 0.0], [2.5, 0.0], [2.5, 2.5]]);
        assert_eq!(points.len(), 6, "{points:?}");
        assert!((points[3][0] - 2.5).abs() < 1e-9 && (points[3][1] - 0.5).abs() < 1e-9);
    }

    #[test]
    fn an_edge_is_named_by_the_way_it_faces() {
        assert_eq!(facing(&[[0.0, -1.0]]), "top");
        assert_eq!(facing(&[[1.0, 0.0]]), "right");
        assert_eq!(facing(&[[0.7, 0.7]]), "lower-right");
        assert_eq!(facing(&[[-1.0, 0.0]]), "left");
    }
}