#![expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::cast_precision_loss,
clippy::cast_possible_wrap,
reason = "decode/encode of the canvas index arithmetic is lossy and sign-changing casts unavoidable"
)]
use crate::tiles::neighbourhood::{CHANNELS, DEFAULT_TILE_SIZE, GRID_SIDE};
const PADDING_REFERENCE_SIDE: u32 = 256;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BakeParams {
pub padding: u32,
pub vertical_exaggeration: f64,
pub contrast: f64,
pub elevation_scale: f64,
pub toon_bands: f64,
pub ambient: f64,
}
impl Default for BakeParams {
fn default() -> Self {
Self {
padding: 0,
vertical_exaggeration: 2.5,
contrast: 2.5,
elevation_scale: 0.0,
toon_bands: 6.0,
ambient: 0.2,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BakedTile {
pub side: u32,
pub gray: Vec<u8>,
pub apron: u32,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Canvas {
rgba: Vec<u8>,
tile_size: usize,
}
impl Canvas {
#[must_use]
pub(crate) fn from_rgba(rgba: Vec<u8>, tile_size: usize) -> Self {
debug_assert_eq!(
rgba.len(),
GRID_SIDE * tile_size * GRID_SIDE * tile_size * CHANNELS,
"canvas buffer must cover the whole 3x3 field"
);
Self { rgba, tile_size }
}
#[must_use]
pub fn uniform(texel: [u8; CHANNELS]) -> Self {
Self::uniform_at(texel, DEFAULT_TILE_SIZE)
}
#[must_use]
pub fn uniform_at(texel: [u8; CHANNELS], tile_size: usize) -> Self {
let side = GRID_SIDE * tile_size;
Self {
rgba: texel.iter().copied().cycle().take(side * side * CHANNELS).collect(),
tile_size,
}
}
#[must_use]
pub const fn tile_size(&self) -> usize {
self.tile_size
}
#[must_use]
const fn side(&self) -> usize {
GRID_SIDE * self.tile_size
}
#[cfg(test)]
pub(crate) fn raw_texel(&self, x: usize, y: usize) -> [u8; CHANNELS] {
let base = (y * self.side() + x) * CHANNELS;
std::array::from_fn(|c| self.rgba[base + c])
}
#[cfg(test)]
pub(crate) fn is_blank(&self) -> bool {
self.rgba.iter().all(|&b| b == 0)
}
#[inline]
fn texel(&self, x: i64, y: i64) -> [f64; CHANNELS] {
let side = self.side();
debug_assert!(
(0..(side as i64 - 1)).contains(&x),
"texel not on canvas in x direction"
);
debug_assert!(
(0..(side as i64 - 1)).contains(&y),
"texel not on canvas in y direction"
);
debug_assert!(self.rgba.len().is_multiple_of(CHANNELS));
let (texels, _) = self.rgba.as_chunks::<CHANNELS>();
texels[y as usize * side + x as usize].map(|c| f64::from(c) / 255.0)
}
#[inline]
fn sample_bilinear(&self, x: f64, y: f64) -> [f64; CHANNELS] {
let fx = x - 0.5;
let fy = y - 0.5;
let x0f = fx.floor();
let y0f = fy.floor();
let tx = fx - x0f;
let ty = fy - y0f;
let (x0, y0) = (x0f as i64, y0f as i64);
let c00 = self.texel(x0, y0);
let c01 = self.texel(x0 + 1, y0);
let c10 = self.texel(x0, y0 + 1);
let c11 = self.texel(x0 + 1, y0 + 1);
std::array::from_fn(|c| {
let top = c01[c].mul_add(tx, c00[c] * (1.0 - tx));
let bot = c11[c].mul_add(tx, c10[c] * (1.0 - tx));
bot.mul_add(ty, top * (1.0 - ty))
})
}
}
fn relief_shade(
nx: [f64; CHANNELS],
ny: [f64; CHANNELS],
alpha: [f64; CHANNELS],
light: [f64; 3],
params: &BakeParams,
) -> [f64; CHANNELS] {
let mut shade = [0.0; CHANNELS];
for i in 0..CHANNELS {
let nx = nx[i].mul_add(2.0, -1.0);
let ny = ny[i].mul_add(2.0, -1.0);
let nz = (1.0 - ny.mul_add(ny, nx * nx)).max(1e-4).sqrt();
let vx = nx * params.vertical_exaggeration;
let vy = ny * params.vertical_exaggeration;
let len = nz.mul_add(nz, vy.mul_add(vy, vx * vx)).sqrt();
let s = (nz / len)
.mul_add(light[2], (vy / len).mul_add(light[1], (vx / len) * light[0]))
.clamp(0.0, 1.0);
let elevation = 1.0 - alpha[i];
let gain = params.contrast * params.elevation_scale.mul_add(elevation, 1.0);
let neutral = light[2].clamp(0.0, 1.0);
shade[i] = (s - neutral).mul_add(gain, neutral).clamp(0.0, 1.0);
}
shade
}
fn band_hard(shade: [f64; CHANNELS], neutral: f64, bands: f64) -> [f64; CHANNELS] {
let band_size = 1.0 / bands;
let mut out = [0.0; CHANNELS];
for i in 0..CHANNELS {
let t = (shade[i] - neutral) / band_size;
let floor_t = t.floor();
let fract = t - floor_t;
let step = if fract >= 0.5 { 1.0 } else { 0.0 };
out[i] = (floor_t + step).mul_add(band_size, neutral).clamp(0.0, 1.0);
}
out
}
#[must_use]
pub fn output_apron(core_side: u32, padding: u32) -> u32 {
(f64::from(padding) * f64::from(core_side) / f64::from(PADDING_REFERENCE_SIDE)).round() as u32
}
#[must_use]
pub fn bake_with_light(canvas: &Canvas, core_side: u32, p: &BakeParams, light: [f64; 3]) -> BakedTile {
let tile_size = canvas.tile_size() as f64;
let scale = tile_size / f64::from(core_side);
let apron = output_apron(core_side, p.padding);
assert!(
(f64::from(apron) + 1.0) * scale <= tile_size,
"padding {} is too large for core_side {core_side}: samples would fall outside the assembled 3x3 canvas",
p.padding
);
let side = core_side + 2 * apron;
let neutral = light[2].clamp(0.0, 1.0);
let banded = p.toon_bands >= 2.0;
let taps = [-0.25 * scale, 0.25 * scale];
let taps_per_texel = (taps.len() * taps.len()) as f64;
let mut gray = vec![0u8; (side as usize) * (side as usize)];
for oy in 0..side {
let cy = f64::mul_add(f64::from(oy) + 0.5 - f64::from(apron), scale, tile_size);
for ox in 0..side {
let cx = f64::mul_add(f64::from(ox) + 0.5 - f64::from(apron), scale, tile_size);
let mut nx = [0.0; CHANNELS];
let mut ny = [0.0; CHANNELS];
let mut alpha = [0.0; CHANNELS];
let mut lane = 0;
for dy in taps {
for dx in taps {
let rgba = canvas.sample_bilinear(cx + dx, cy + dy);
nx[lane] = rgba[0];
ny[lane] = rgba[1];
alpha[lane] = rgba[3];
lane += 1;
}
}
let mut shades = relief_shade(nx, ny, alpha, light, p);
if banded {
shades = band_hard(shades, neutral, p.toon_bands);
}
let acc = shades[0]
.algebraic_add(shades[1])
.algebraic_add(shades[2])
.algebraic_add(shades[3]);
let acc = acc.algebraic_div(taps_per_texel);
let one_minus_ambient = 1.0_f64.algebraic_sub(p.ambient);
let acc = one_minus_ambient.algebraic_mul(acc);
let shade = p.ambient.algebraic_add(acc);
let shade = shade.algebraic_mul(255.0).round() as u8;
gray[(oy * side + ox) as usize] = shade;
}
}
BakedTile { side, gray, apron }
}
#[cfg(test)]
mod tests {
use rstest::rstest;
use super::*;
const LIGHT_FROM_OVERHEAD: [f64; 3] = [0.0, 0.0, 1.0];
const SLOPED_TEXEL: [u8; CHANNELS] = [160, 100, 200, 220];
#[rstest]
#[case(256, 8, 8)]
#[case(512, 8, 16)]
#[case(384, 8, 12)]
#[case::rounds_away_from_zero(384, 1, 2)]
#[case(512, 0, 0)]
fn apron_rescales_with_the_core(#[case] core: u32, #[case] padding: u32, #[case] expected: u32) {
assert_eq!(output_apron(core, padding), expected);
}
#[test]
fn the_default_bake_is_exactly_the_core_size() {
let baked = bake_with_light(
&Canvas::uniform(SLOPED_TEXEL),
512,
&BakeParams::default(),
LIGHT_FROM_OVERHEAD,
);
assert_eq!(baked.apron, 0);
assert_eq!(baked.side, 512);
assert_eq!(baked.gray.len(), 512 * 512);
}
#[rstest]
#[case(256, 8)]
#[case(512, 8)]
#[case(512, 0)]
#[case(384, 1)]
fn bake_dimensions_agree_with_the_apron_formula(#[case] core: u32, #[case] padding: u32) {
let params = BakeParams {
padding,
..BakeParams::default()
};
let baked = bake_with_light(&Canvas::uniform(SLOPED_TEXEL), core, ¶ms, LIGHT_FROM_OVERHEAD);
let expected_apron = (f64::from(padding) * f64::from(core) / f64::from(PADDING_REFERENCE_SIDE)).round() as u32;
assert_eq!(baked.apron, expected_apron);
assert_eq!(baked.side, core + 2 * expected_apron);
assert_eq!(baked.gray.len(), (baked.side as usize).pow(2));
}
#[test]
fn a_uniform_field_bakes_to_a_single_tone() {
let baked = bake_with_light(
&Canvas::uniform(SLOPED_TEXEL),
64,
&BakeParams {
padding: 8,
..BakeParams::default()
},
[-0.5, 0.5, 0.7],
);
let first = baked.gray[0];
assert!(
baked.gray.iter().all(|&g| g == first),
"a uniform normal field must bake to one flat tone"
);
}
#[test]
fn banding_switches_off_below_two_bands() {
let canvas = Canvas::uniform(SLOPED_TEXEL);
let light = [-0.5, 0.5, 0.7];
let smooth = |bands| {
bake_with_light(
&canvas,
32,
&BakeParams {
toon_bands: bands,
..BakeParams::default()
},
light,
)
.gray[0]
};
assert_eq!(smooth(0.0), smooth(1.9), "any value below 2 disables banding");
assert_ne!(smooth(0.0), smooth(3.0), "banding must actually quantise");
}
fn framed_canvas(tile_size: usize, centre: [u8; CHANNELS], surround: [u8; CHANNELS]) -> Canvas {
let side = GRID_SIDE * tile_size;
let mut rgba = Vec::with_capacity(side * side * CHANNELS);
for y in 0..side {
for x in 0..side {
let in_centre = (tile_size..2 * tile_size).contains(&x) && (tile_size..2 * tile_size).contains(&y);
rgba.extend_from_slice(if in_centre { ¢re } else { &surround });
}
}
Canvas::from_rgba(rgba, tile_size)
}
#[rstest]
#[case(DEFAULT_TILE_SIZE)]
#[case(2 * DEFAULT_TILE_SIZE)]
fn the_bake_frames_the_centre_tile_at_the_sources_own_size(#[case] tile_size: usize) {
let core = u32::try_from(tile_size).expect("a tile side");
let params = BakeParams::default();
let framed = bake_with_light(
&framed_canvas(tile_size, SLOPED_TEXEL, [10, 240, 30, 40]),
core,
¶ms,
LIGHT_FROM_OVERHEAD,
);
let centre_only = bake_with_light(
&Canvas::uniform_at(SLOPED_TEXEL, tile_size),
core,
¶ms,
LIGHT_FROM_OVERHEAD,
);
let side = framed.side as usize;
let interior = |gray: &[u8]| -> Vec<u8> {
(1..side - 1)
.flat_map(|y| (1..side - 1).map(move |x| (x, y)))
.map(|(x, y)| gray[y * side + x])
.collect()
};
assert_eq!(
interior(&framed.gray),
interior(¢re_only.gray),
"the bake must read the centre tile, not a crop of the field"
);
}
fn varied_canvas() -> Canvas {
let side = GRID_SIDE * DEFAULT_TILE_SIZE;
let mut rgba = vec![0u8; side * side * CHANNELS];
for y in 0..side {
for x in 0..side {
let base = (y * side + x) * CHANNELS;
rgba[base] = ((x * 37 + y * 17) % 256) as u8;
rgba[base + 1] = ((x * 11 + y * 53) % 256) as u8;
rgba[base + 2] = 128;
rgba[base + 3] = ((x * 3 + y * 29) % 256) as u8;
}
}
Canvas::from_rgba(rgba, DEFAULT_TILE_SIZE)
}
#[test]
fn bakes_a_varied_field_to_the_pinned_reference_bytes() {
let canvas = varied_canvas();
let light = [-0.5, 0.5, 0.7];
let idx = [0usize, 17, 63, 64, 700, 2000, 4032, 4095];
let baked = bake_with_light(&canvas, 64, &BakeParams::default(), light);
let samples: Vec<u8> = idx.iter().map(|&i| baked.gray[i]).collect();
assert_eq!(samples, vec![150, 150, 66, 100, 107, 109, 165, 107]);
let smooth = BakeParams {
toon_bands: 0.0,
..BakeParams::default()
};
let baked = bake_with_light(&canvas, 64, &smooth, light);
let samples: Vec<u8> = idx.iter().map(|&i| baked.gray[i]).collect();
assert_eq!(samples, vec![149, 147, 61, 93, 102, 108, 167, 102]);
}
#[test]
fn ambient_sets_the_shadow_floor() {
let light = [0.0, 0.0, 1.0];
let canvas = Canvas::uniform([255, 255, 0, 255]);
for ambient in [0.0, 0.25, 0.5] {
let baked = bake_with_light(
&canvas,
16,
&BakeParams {
ambient,
..BakeParams::default()
},
light,
);
let floor = (ambient * 255.0).round() as u8;
assert_eq!(baked.gray[0], floor, "ambient {ambient} must floor the darkest tone");
}
}
}