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};
pub const MAGNIFICATION: f64 = 2.0;
pub const OUTSIDE_PX: f64 = 36.0;
pub const INSIDE_PX: f64 = 36.0;
pub const MAX_HEIGHT: u32 = 2576;
const BAND_HEIGHT: u32 = 32;
const ROW_LABEL_HEIGHT: u32 = 22;
const GAP_PX: u32 = 12;
const MIN_PIECE_PX: u32 = 160;
const WORK_WIDTH: u32 = 320;
const WORK_BLUR_SIGMA: f64 = 2.0;
const SMOOTH_BELOW: f64 = 4.0;
const LIT_FROM: f64 = 60.0;
const MIN_SHARE: f64 = 0.05;
const MIN_FILL: f64 = 0.75;
const BORDER_PX: f64 = 8.0;
const MIN_RUN_PX: f64 = 40.0;
const TANGENT_REACH: usize = 12;
const MAX_CORNER_CANDIDATES: usize = 40;
const QUALITY: u8 = 90;
const BAND: Rgb<u8> = Rgb([24, 24, 24]);
const TEXT: Rgb<u8> = Rgb([235, 235, 235]);
const OFF_FRAME: Rgb<u8> = Rgb([32, 32, 32]);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LocatedBy {
Calibration,
Frame,
}
#[derive(Debug, Clone, Copy)]
pub struct SheetEdgesInputs<'a> {
pub frame_jpeg: &'a [u8],
pub calibration: Option<(&'a CameraCalibration, &'a str)>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct EdgeStrip {
pub name: &'static str,
pub points: Vec<[f64; 2]>,
pub normals: Vec<[f64; 2]>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Piece {
pub strip: usize,
pub from_px: u32,
pub rect: [u32; 4],
}
#[derive(Debug, Clone, PartialEq)]
pub struct SheetEdges {
pub jpeg: Vec<u8>,
pub width: u32,
pub height: u32,
pub located_by: LocatedBy,
pub whole_scale: f64,
pub close_up_scale: f64,
pub outline: Vec<[f64; 2]>,
pub strips: Vec<EdgeStrip>,
pub pieces: Vec<Piece>,
pub outside_px: f64,
}
impl SheetEdges {
#[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,
))
}
}
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))
}
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)
}
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
}
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,
]
}
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))
}
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(¢res);
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())
}
#[derive(Debug, Clone, Copy, Default)]
struct Region {
area: f64,
grey: f64,
}
impl Region {
fn mean(self) -> f64 {
self.grey / self.area.max(1.0)
}
fn share(self, total: f64) -> f64 {
self.area / total
}
fn weight(self) -> f64 {
self.area * self.mean() * self.mean()
}
}
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)
}
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
}
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
}
fn clockwise(mut polygon: Vec<[f64; 2]>) -> Vec<[f64; 2]> {
if polygon_area(&polygon) < 0.0 {
polygon.reverse();
}
polygon
}
fn corners(hull: &[[f64; 2]]) -> [usize; 4] {
let mut kept: Vec<usize> = (0..hull.len()).collect();
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
}
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
}
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
}
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
}
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()
}
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]]);
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()]
}
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
}
fn index_of(value: f64) -> usize {
usize::try_from(pixels(value.floor())).unwrap_or(0)
}
fn coordinate(index: usize) -> f64 {
f64::from(u32::try_from(index).unwrap_or(u32::MAX))
}
fn channel_of(value: f64) -> u8 {
u8::try_from(pixels(value).min(255)).unwrap_or(u8::MAX)
}
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");
}
}