pub struct FlakesTexture;
impl FlakesTexture {
#[allow(clippy::new_ret_no_self)]
pub fn new(width: u32, height: u32, mut random: impl FnMut() -> f64) -> Vec<u8> {
let mut pixels = [127u8, 127, 255, 255].repeat((width * height) as usize);
for _ in 0..4000 {
let x = random() * width as f64;
let y = random() * height as f64;
let r = random() * 3.0 + 3.0;
let mut nx = random() * 2.0 - 1.0;
let mut ny = random() * 2.0 - 1.0;
let mut nz = 1.5;
let l = (nx * nx + ny * ny + nz * nz).sqrt();
nx /= l;
ny /= l;
nz /= l;
let color = [
css_channel(nx * 127.0 + 127.0),
css_channel(ny * 127.0 + 127.0),
css_channel(nz * 255.0),
];
fill_circle(&mut pixels, width, height, x, y, r, color);
}
pixels
}
}
fn css_channel(value: f64) -> u8 {
value.clamp(0.0, 255.0).round() as u8
}
fn fill_circle(pixels: &mut [u8], width: u32, height: u32, x: f64, y: f64, r: f64, color: [u8; 3]) {
let reach = r + 0.5;
let x0 = (x - reach).floor().max(0.0) as u32;
let y0 = (y - reach).floor().max(0.0) as u32;
let x1 = (x + reach).ceil().min(width as f64) as u32;
let y1 = (y + reach).ceil().min(height as f64) as u32;
for py in y0..y1 {
for px in x0..x1 {
let dx = px as f64 + 0.5 - x;
let dy = py as f64 + 0.5 - y;
let coverage = (r - (dx * dx + dy * dy).sqrt() + 0.5).clamp(0.0, 1.0);
if coverage == 0.0 {
continue;
}
let i = ((py * width + px) * 4) as usize;
for c in 0..3 {
let dst = pixels[i + c] as f64;
pixels[i + c] = (dst + (color[c] as f64 - dst) * coverage).round() as u8;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::DeterministicRandom;
#[test]
fn first_flake_matches_the_page() {
let mut random = DeterministicRandom::new();
random.skip(5);
let draws: Vec<f64> = (0..5).map(|_| random.next()).collect();
assert!((draws[0] * 512.0 - 90.09996055904776).abs() < 1e-9);
assert!((draws[1] * 512.0 - 339.59546484192833).abs() < 1e-9);
assert!((draws[2] * 3.0 + 3.0 - 4.472265021508065).abs() < 1e-9);
let mut random = DeterministicRandom::new();
random.skip(5);
let pixels = FlakesTexture::new(512, 512, || random.next());
assert_eq!(pixels.len(), 512 * 512 * 4);
let i = (339 * 512 + 90) * 4;
assert_eq!(&pixels[i..i + 4], &[0xc3, 0x78, 0xd7, 0xff]);
}
}