use std::iter::FusedIterator;
use crate::Size;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Grid<T> {
width: u16,
height: u16,
cells: Vec<T>,
}
impl<T> Default for Grid<T> {
fn default() -> Self {
Self {
width: 0,
height: 0,
cells: Vec::new(),
}
}
}
impl<T: Clone> Grid<T> {
pub fn new(size: Size, fill: T) -> Self {
Self {
width: size.width(),
height: size.height(),
cells: vec![fill; size.area()],
}
}
pub fn fill(&mut self, v: T) {
self.cells.fill(v);
}
pub fn resize(&mut self, size: Size, fill: T) {
let (ow, oh) = (usize::from(self.width), usize::from(self.height));
let (nw, nh) = (usize::from(size.width()), usize::from(size.height()));
if (ow, oh) == (nw, nh) {
return;
}
let (mw, mh) = (ow.min(nw), oh.min(nh));
let new_len = nw * nh;
if new_len > self.cells.len() {
self.cells.resize(new_len, fill.clone());
}
let mut shift = |y: usize, x: usize| self.cells.swap(y * ow + x, y * nw + x);
if nw <= ow {
(0..mh).for_each(|y| (0..mw).for_each(|x| shift(y, x)));
} else {
(0..mh)
.rev()
.for_each(|y| (0..mw).rev().for_each(|x| shift(y, x)));
}
self.cells.truncate(new_len);
if mw < nw {
for y in 0..mh {
self.cells[y * nw + mw..(y + 1) * nw].fill(fill.clone());
}
}
self.cells[mh * nw..].fill(fill);
self.width = size.width();
self.height = size.height();
}
fn reshape(&mut self, size: Size, fill: T) {
self.cells.clear();
self.cells.resize(size.area(), fill);
self.width = size.width();
self.height = size.height();
}
}
impl<T> Grid<T> {
#[inline]
pub fn size(&self) -> Size {
Size::new(self.width, self.height)
}
#[inline]
pub fn width(&self) -> u16 {
self.width
}
#[inline]
pub fn height(&self) -> u16 {
self.height
}
#[inline]
pub fn len(&self) -> usize {
self.cells.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.cells.is_empty()
}
#[inline]
fn size_is(&self, size: Size) -> bool {
(self.width, self.height) == (size.width(), size.height())
}
#[inline]
fn index(&self, x: i32, y: i32) -> Option<usize> {
let in_x = (0..i32::from(self.width)).contains(&x);
let in_y = (0..i32::from(self.height)).contains(&y);
(in_x && in_y).then(|| y as usize * usize::from(self.width) + x as usize)
}
#[inline]
pub fn get(&self, x: i32, y: i32) -> Option<&T> {
self.index(x, y).map(|i| &self.cells[i])
}
#[inline]
pub fn get_mut(&mut self, x: i32, y: i32) -> Option<&mut T> {
self.index(x, y).map(|i| &mut self.cells[i])
}
#[inline]
pub fn set(&mut self, x: i32, y: i32, v: T) -> bool {
match self.get_mut(x, y) {
Some(cell) => {
*cell = v;
true
}
None => false,
}
}
pub fn iter(&self) -> Iter<'_, T> {
Iter {
cells: self.cells.iter(),
width: i32::from(self.width),
x: 0,
y: 0,
}
}
#[inline]
pub fn as_slice(&self) -> &[T] {
&self.cells
}
#[inline]
pub fn as_mut_slice(&mut self) -> &mut [T] {
&mut self.cells
}
pub fn neighbors(&self, x: i32, y: i32, hood: Hood, edges: Edges) -> Neighbors {
let offsets: &'static [(i32, i32)] = match hood {
Hood::VonNeumann => &VON_NEUMANN,
Hood::Moore => &MOORE,
};
let (w, h) = (i32::from(self.width), i32::from(self.height));
Neighbors {
x,
y,
w,
h,
edges,
offsets: if self.index(x, y).is_some() {
offsets
} else {
&[]
},
dedup: edges == Edges::Wrap && (w < 3 || h < 3),
seen: [(0, 0); 8],
n_seen: 0,
}
}
pub fn step(&mut self, scratch: &mut Grid<T>, mut rule: impl FnMut(&Grid<T>, i32, i32) -> T) {
scratch.cells.clear();
scratch.cells.reserve_exact(self.cells.len());
for y in 0..i32::from(self.height) {
for x in 0..i32::from(self.width) {
scratch.cells.push(rule(self, x, y));
}
}
scratch.width = self.width;
scratch.height = self.height;
std::mem::swap(self, scratch);
}
}
#[inline]
pub fn centre_of(d: f64, dn: usize, sn: usize) -> f64 {
(d + 0.5) * sn as f64 / dn as f64 - 0.5
}
pub fn regrid_bilinear(field: &mut Grid<f32>, size: Size, scratch: &mut Grid<f32>) {
if field.is_empty() || field.size_is(size) {
return;
}
scratch.reshape(size, 0.0);
resample_bilinear(field, scratch);
std::mem::swap(field, scratch);
}
pub fn regrid_nearest<T: Clone>(field: &mut Grid<T>, size: Size, scratch: &mut Grid<T>) {
if field.is_empty() || field.size_is(size) {
return;
}
let fill = field.cells[0].clone();
scratch.reshape(size, fill);
resample_nearest(field, scratch);
std::mem::swap(field, scratch);
}
pub fn resample_bilinear(src: &Grid<f32>, dst: &mut Grid<f32>) {
if src.is_empty() || dst.is_empty() {
return;
}
let (sw, sh) = (usize::from(src.width), usize::from(src.height));
let (dw, dh) = (usize::from(dst.width), usize::from(dst.height));
for (y, row) in dst.cells.chunks_exact_mut(dw).enumerate() {
let (y0, y1, fy) = bilinear_taps(y, dh, sh);
let (r0, r1) = (&src.cells[y0 * sw..][..sw], &src.cells[y1 * sw..][..sw]);
for (x, out) in row.iter_mut().enumerate() {
let (x0, x1, fx) = bilinear_taps(x, dw, sw);
*out = bilerp(r0[x0], r0[x1], r1[x0], r1[x1], fx, fy);
}
}
}
#[inline]
fn bilinear_taps(d: usize, dn: usize, sn: usize) -> (usize, usize, f32) {
let s = centre_of(d as f64, dn, sn).clamp(0.0, (sn - 1) as f64);
let i0 = s as usize; let i1 = (i0 + 1).min(sn - 1);
(i0, i1, (s - i0 as f64) as f32)
}
#[inline(always)]
fn lerp32(a: f32, b: f32, f: f32) -> f32 {
if f == 0.0 { a } else { a + (b - a) * f }
}
#[inline(always)]
fn bilerp(top0: f32, top1: f32, bottom0: f32, bottom1: f32, fx: f32, fy: f32) -> f32 {
lerp32(lerp32(top0, top1, fx), lerp32(bottom0, bottom1, fx), fy)
}
#[inline]
fn nearest_tap(d: usize, dn: usize, sn: usize) -> usize {
((2 * d + 1) * sn / (2 * dn)).min(sn - 1)
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Tap {
i0: u16,
i1: u16,
near: u16,
f: f32,
}
impl Tap {
fn new(d: usize, dn: usize, sn: usize) -> Self {
let (i0, i1, f) = bilinear_taps(d, dn, sn);
Self {
i0: i0 as u16,
i1: i1 as u16,
near: nearest_tap(d, dn, sn) as u16,
f,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct SampleMap {
src: (u16, u16),
xs: Vec<Tap>,
ys: Vec<Tap>,
cxs: Vec<Cubic>,
cys: Vec<Cubic>,
magnification: f32,
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Cubic {
i: [u16; 4],
w: [f32; 4],
}
impl Cubic {
fn new(d: usize, dn: usize, sn: usize) -> Self {
let s = centre_of(d as f64, dn, sn).clamp(0.0, (sn.max(1) - 1) as f64);
let i1 = s as usize; let last = sn.max(1) - 1;
let t = s - i1 as f64;
let (t2, t3) = (t * t, t * t * t);
let w = [
0.5 * (-t3 + 2.0 * t2 - t),
0.5 * (3.0 * t3 - 5.0 * t2 + 2.0),
0.5 * (-3.0 * t3 + 4.0 * t2 + t),
0.5 * (t3 - t2),
];
Self {
i: [
i1.saturating_sub(1) as u16,
i1 as u16,
(i1 + 1).min(last) as u16,
(i1 + 2).min(last) as u16,
],
w: w.map(|w| w as f32),
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct CubicRow<'a> {
xs: &'a [Cubic],
rows: [&'a [f32]; 4],
wy: [f32; 4],
}
impl CubicRow<'_> {
#[inline(always)]
pub fn at(&self, x: i32) -> f32 {
let Some(last) = self.xs.len().checked_sub(1) else {
return 0.0;
};
if self.rows[0].is_empty() {
return 0.0;
}
let tx = self.xs[usize::try_from(x).map_or(0, |i| i.min(last))];
let [a, b, c, d] = tx.i.map(usize::from);
let across = |r: &[f32]| tx.w[0] * r[a] + tx.w[1] * r[b] + tx.w[2] * r[c] + tx.w[3] * r[d];
let v = self.wy[0] * across(self.rows[0])
+ self.wy[1] * across(self.rows[1])
+ self.wy[2] * across(self.rows[2])
+ self.wy[3] * across(self.rows[3]);
let (r1, r2) = (self.rows[1], self.rows[2]);
let lo = r1[b].min(r1[c]).min(r2[b]).min(r2[c]);
let hi = r1[b].max(r1[c]).max(r2[b]).max(r2[c]);
v.max(lo).min(hi)
}
}
impl SampleMap {
pub fn rebuild(&mut self, src: Size, dst: Size) {
let (sw, sh) = (usize::from(src.width()), usize::from(src.height()));
let (dw, dh) = (usize::from(dst.width()), usize::from(dst.height()));
self.src = (src.width(), src.height());
self.xs.clear();
self.xs.extend((0..dw).map(|x| Tap::new(x, dw, sw)));
self.ys.clear();
self.ys.extend((0..dh).map(|y| Tap::new(y, dh, sh)));
self.cxs.clear();
self.cxs.extend((0..dw).map(|x| Cubic::new(x, dw, sw)));
self.cys.clear();
self.cys.extend((0..dh).map(|y| Cubic::new(y, dh, sh)));
let ratio = |d: usize, s: usize| if s == 0 { 0.0 } else { d as f32 / s as f32 };
self.magnification = if dw == 0 || dh == 0 {
0.0
} else {
ratio(dw, sw).max(ratio(dh, sh))
};
}
#[inline]
pub fn magnification(&self) -> f32 {
self.magnification
}
#[inline]
pub fn sample_cubic(&self, src: &Grid<f32>, x: i32, y: i32) -> f32 {
self.row_cubic(src, y).at(x)
}
#[inline(always)]
pub fn row_cubic<'a>(&'a self, src: &'a Grid<f32>, y: i32) -> CubicRow<'a> {
let mut out = CubicRow {
xs: &[],
rows: [&[]; 4],
wy: [0.0; 4],
};
if (src.width, src.height) != self.src {
return out;
}
let Some(last) = self.cys.len().checked_sub(1) else {
return out;
};
let ty = self.cys[usize::try_from(y).map_or(0, |i| i.min(last))];
let w = usize::from(src.width);
for (row, &i) in out.rows.iter_mut().zip(&ty.i) {
*row = &src.cells[usize::from(i) * w..][..w];
}
out.xs = &self.cxs;
out.wy = ty.w;
out
}
#[inline(always)]
fn taps(&self, x: i32, y: i32) -> Option<(Tap, Tap)> {
let pick = |t: &[Tap], i: i32| {
let last = t.len().checked_sub(1)?;
Some(t[usize::try_from(i).map_or(0, |i| i.min(last))])
};
Some((pick(&self.xs, x)?, pick(&self.ys, y)?))
}
#[inline(always)]
pub fn sample(&self, src: &Grid<f32>, x: i32, y: i32) -> f32 {
if (src.width, src.height) != self.src {
return 0.0;
}
let Some((tx, ty)) = self.taps(x, y) else {
return 0.0;
};
let w = usize::from(src.width);
let row = |i: u16| &src.cells[usize::from(i) * w..][..w];
let (r0, r1) = (row(ty.i0), row(ty.i1));
let (x0, x1) = (usize::from(tx.i0), usize::from(tx.i1));
bilerp(r0[x0], r0[x1], r1[x0], r1[x1], tx.f, ty.f)
}
#[inline(always)]
pub fn row<'a>(&'a self, src: &'a Grid<f32>, y: i32) -> MapRow<'a> {
let empty = MapRow {
xs: &[],
r0: &[],
r1: &[],
fy: 0.0,
};
if (src.width, src.height) != self.src {
return empty;
}
let Some(last) = self.ys.len().checked_sub(1) else {
return empty;
};
let ty = self.ys[usize::try_from(y).map_or(0, |i| i.min(last))];
let w = usize::from(src.width);
let row = |i: u16| &src.cells[usize::from(i) * w..][..w];
MapRow {
xs: &self.xs,
r0: row(ty.i0),
r1: row(ty.i1),
fy: ty.f,
}
}
#[inline(always)]
pub fn nearest(&self, x: i32, y: i32) -> (i32, i32) {
self.taps(x, y)
.map_or((0, 0), |(tx, ty)| (i32::from(tx.near), i32::from(ty.near)))
}
}
#[derive(Debug, Clone, Copy)]
pub struct MapRow<'a> {
xs: &'a [Tap],
r0: &'a [f32],
r1: &'a [f32],
fy: f32,
}
impl MapRow<'_> {
#[inline(always)]
pub fn at(&self, x: i32) -> f32 {
let Some(last) = self.xs.len().checked_sub(1) else {
return 0.0;
};
if self.r0.is_empty() {
return 0.0;
}
let tx = self.xs[usize::try_from(x).map_or(0, |i| i.min(last))];
let (x0, x1) = (usize::from(tx.i0), usize::from(tx.i1));
bilerp(
self.r0[x0],
self.r0[x1],
self.r1[x0],
self.r1[x1],
tx.f,
self.fy,
)
}
}
pub fn laplacian9(src: &Grid<f32>, dst: &mut Grid<f32>, edges: Edges) {
let (w, h) = (usize::from(src.width), usize::from(src.height));
dst.cells.clear();
dst.cells.resize(w * h, 0.0);
dst.width = src.width;
dst.height = src.height;
if w == 0 || h == 0 {
return;
}
let around = |i: usize, n: usize| match edges {
Edges::Wrap => ((i + n - 1) % n, (i + 1) % n),
Edges::Clip => (i.saturating_sub(1), (i + 1).min(n - 1)),
};
let row = |y: usize| &src.cells[y * w..][..w];
for (y, out) in dst.cells.chunks_exact_mut(w).enumerate() {
let (yn, ys) = around(y, h);
let (north, mid, south) = (row(yn), row(y), row(ys));
for (x, o) in out.iter_mut().enumerate() {
let (xw, xe) = around(x, w);
let orth = (mid[xw] + mid[xe]) + (north[x] + south[x]);
let diag = (north[xw] + north[xe]) + (south[xw] + south[xe]);
*o = (4.0 * orth + diag - 20.0 * mid[x]) / 6.0;
}
}
}
pub fn resample_nearest<T: Clone>(src: &Grid<T>, dst: &mut Grid<T>) {
if src.is_empty() || dst.is_empty() {
return;
}
let (sw, sh) = (usize::from(src.width), usize::from(src.height));
let (dw, dh) = (usize::from(dst.width), usize::from(dst.height));
for (y, row) in dst.cells.chunks_exact_mut(dw).enumerate() {
let src_row = &src.cells[nearest_tap(y, dh, sh) * sw..][..sw];
for (x, out) in row.iter_mut().enumerate() {
out.clone_from(&src_row[nearest_tap(x, dw, sw)]);
}
}
}
pub fn lattice_for(display: Size, max_nodes: usize, bucket: f64) -> Size {
if max_nodes == 0 {
return Size::new(1, 1);
}
let (dw, dh) = (display.width(), display.height());
let aspect = f64::from(dw) / f64::from(dh);
let snapped = if bucket > 1.0 {
let step = bucket.ln();
((aspect.ln() / step).round() * step).exp()
} else {
aspect
};
let aspect = if snapped.is_finite() && snapped > 0.0 {
snapped
} else {
aspect
};
let full = lattice_for_aspect(aspect, max_nodes);
Size::new(full.width().min(dw), full.height().min(dh))
}
pub fn lattice_for_aspect(aspect: f64, max_nodes: usize) -> Size {
if max_nodes == 0 {
return Size::new(1, 1);
}
let h_ideal = (max_nodes as f64 / aspect).sqrt();
let h = (h_ideal as usize).clamp(1, max_nodes);
let w = ((h_ideal * aspect) as usize).clamp(1, max_nodes / h);
let axis = |n: usize| u16::try_from(n).unwrap_or(u16::MAX);
Size::new(axis(w), axis(h))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Hood {
VonNeumann,
Moore,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Edges {
Clip,
Wrap,
}
const VON_NEUMANN: [(i32, i32); 4] = [(0, -1), (-1, 0), (1, 0), (0, 1)];
const MOORE: [(i32, i32); 8] = [
(-1, -1),
(0, -1),
(1, -1),
(-1, 0),
(1, 0),
(-1, 1),
(0, 1),
(1, 1),
];
#[derive(Debug, Clone)]
pub struct Iter<'a, T> {
cells: std::slice::Iter<'a, T>,
width: i32,
x: i32,
y: i32,
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = ((i32, i32), &'a T);
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let cell = self.cells.next()?;
let pos = (self.x, self.y);
self.x += 1;
if self.x == self.width {
self.x = 0;
self.y += 1;
}
Some((pos, cell))
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.cells.size_hint()
}
}
impl<T> ExactSizeIterator for Iter<'_, T> {}
impl<T> FusedIterator for Iter<'_, T> {}
#[derive(Debug, Clone)]
pub struct Neighbors {
x: i32,
y: i32,
w: i32,
h: i32,
edges: Edges,
offsets: &'static [(i32, i32)],
dedup: bool,
seen: [(i32, i32); 8],
n_seen: usize,
}
impl Iterator for Neighbors {
type Item = (i32, i32);
fn next(&mut self) -> Option<(i32, i32)> {
while let Some((&(dx, dy), rest)) = self.offsets.split_first() {
self.offsets = rest;
let (mut nx, mut ny) = (self.x + dx, self.y + dy);
match self.edges {
Edges::Clip => {
if !(0..self.w).contains(&nx) || !(0..self.h).contains(&ny) {
continue;
}
}
Edges::Wrap => {
nx = nx.rem_euclid(self.w);
ny = ny.rem_euclid(self.h);
}
}
if self.dedup {
let p = (nx, ny);
if p == (self.x, self.y) || self.seen[..self.n_seen].contains(&p) {
continue;
}
self.seen[self.n_seen] = p;
self.n_seen += 1;
}
return Some((nx, ny));
}
None
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some(self.offsets.len()))
}
}
impl FusedIterator for Neighbors {}