M0.1–M0.7: workspace, time/geom/color/keyframe/project/raster/path/text/effects/render crates

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-01 14:05:20 -04:00
co-authored by Claude Opus 5.5
parent 9f19158a59
commit 808cd490cd
76 changed files with 12319 additions and 3 deletions
+191
View File
@@ -0,0 +1,191 @@
//! Blurs: separable box passes (exact running sums) approximating Gaussians, plus directional
//! and radial (spin/zoom) blurs.
use rayon::prelude::*;
use crate::{Image, Px};
/// One horizontal box pass of radius `r` (window 2r+1) over each row; `repeat` = edge pixels
/// extend, otherwise transparent.
fn box_h(img: &Image, r: usize, repeat: bool) -> Image {
if r == 0 {
return img.clone();
}
let w = img.width as usize;
let mut out = Image::new(img.width, img.height);
let norm = 1.0 / (2 * r + 1) as f32;
out.data.par_chunks_mut(w).zip(img.data.par_chunks(w)).for_each(|(o, row)| {
let get = |i: isize| -> Px {
if i < 0 {
if repeat { row[0] } else { [0.0; 4] }
} else if i as usize >= w {
if repeat { row[w - 1] } else { [0.0; 4] }
} else {
row[i as usize]
}
};
let mut acc = [0.0f32; 4];
for i in -(r as isize)..=(r as isize) {
let p = get(i);
for c in 0..4 {
acc[c] += p[c];
}
}
for x in 0..w {
o[x] = acc.map(|v| v * norm);
let add = get(x as isize + r as isize + 1);
let sub = get(x as isize - r as isize);
for c in 0..4 {
acc[c] += add[c] - sub[c];
}
}
});
out
}
fn transpose(img: &Image) -> Image {
let (w, h) = (img.width as usize, img.height as usize);
let mut out = Image::new(img.height, img.width);
out.data.par_chunks_mut(h.max(1)).enumerate().for_each(|(x, col)| {
for y in 0..h {
col[y] = img.data[y * w + x];
}
});
out
}
/// Box radii for `n` passes approximating a Gaussian of `sigma` (Kovesi / "boxes for Gauss").
fn box_radii(sigma: f64, n: usize) -> Vec<usize> {
if sigma <= 0.0 {
return vec![0; n];
}
let w_ideal = (12.0 * sigma * sigma / n as f64 + 1.0).sqrt();
let mut wl = w_ideal.floor() as i64;
if wl % 2 == 0 {
wl -= 1;
}
let wu = wl + 2;
let m_ideal = (12.0 * sigma * sigma - (n as i64 * wl * wl) as f64 - 4.0 * n as f64 * wl as f64 - 3.0 * n as f64) / (-4.0 * wl as f64 - 4.0);
let m = m_ideal.round() as i64;
(0..n as i64).map(|i| (((if i < m { wl } else { wu }) - 1) / 2).max(0) as usize).collect()
}
/// Separable box blur with given radii, `iterations` passes.
pub fn box_blur(img: &Image, rx: usize, ry: usize, iterations: usize, repeat: bool) -> Image {
let mut cur = img.clone();
for _ in 0..iterations.max(1) {
cur = box_h(&cur, rx, repeat);
}
if ry > 0 {
let mut t = transpose(&cur);
for _ in 0..iterations.max(1) {
t = box_h(&t, ry, repeat);
}
cur = transpose(&t);
}
cur
}
/// Gaussian blur with standard deviations in pixels (3 box passes per axis).
pub fn gaussian_blur(img: &Image, sigma_x: f64, sigma_y: f64, repeat: bool) -> Image {
let mut cur = img.clone();
if sigma_x > 0.05 {
for r in box_radii(sigma_x, 3) {
cur = box_h(&cur, r, repeat);
}
}
if sigma_y > 0.05 {
let mut t = transpose(&cur);
for r in box_radii(sigma_y, 3) {
t = box_h(&t, r, repeat);
}
cur = transpose(&t);
}
cur
}
/// Motion blur along `angle_deg` (0 = vertical in AE's Directional Blur, measured clockwise from
/// up) over `length` pixels.
pub fn directional_blur(img: &Image, angle_deg: f64, length: f64) -> Image {
if length < 0.5 {
return img.clone();
}
let a = angle_deg.to_radians();
let (dx, dy) = (a.sin(), -a.cos());
let n = (length.ceil() as usize * 2 + 1).clamp(3, 257);
let mut out = Image::new(img.width, img.height);
out.rows_mut().for_each(|(y, row)| {
for (x, px) in row.iter_mut().enumerate() {
let mut acc = [0.0f32; 4];
for i in 0..n {
let t = (i as f64 / (n - 1) as f64 - 0.5) * length;
let p = img.sample_bilinear(x as f64 + 0.5 + dx * t, y as f64 + 0.5 + dy * t);
for c in 0..4 {
acc[c] += p[c];
}
}
*px = acc.map(|v| v / n as f32);
}
});
out
}
/// Radial blur around `center`: `spin` (degrees) or zoom (`amount` as a fraction of distance).
pub fn radial_blur(img: &Image, center: (f64, f64), amount: f64, zoom: bool) -> Image {
if amount.abs() < 1e-6 {
return img.clone();
}
let n = 32usize;
let mut out = Image::new(img.width, img.height);
out.rows_mut().for_each(|(y, row)| {
for (x, px) in row.iter_mut().enumerate() {
let (vx, vy) = (x as f64 + 0.5 - center.0, y as f64 + 0.5 - center.1);
let mut acc = [0.0f32; 4];
for i in 0..n {
let t = i as f64 / (n - 1) as f64 - 0.5;
let (sx, sy) = if zoom {
let k = 1.0 + t * amount;
(center.0 + vx * k, center.1 + vy * k)
} else {
let (s, c) = (t * amount).to_radians().sin_cos();
(center.0 + vx * c - vy * s, center.1 + vx * s + vy * c)
};
let p = img.sample_bilinear(sx, sy);
for ch in 0..4 {
acc[ch] += p[ch];
}
}
*px = acc.map(|v| v / n as f32);
}
});
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gaussian_preserves_mass() {
let mut img = Image::new(64, 64);
img.set(32, 32, [1.0; 4]);
let b = gaussian_blur(&img, 4.0, 4.0, false);
let sum: f32 = b.data.iter().map(|p| p[3]).sum();
assert!((sum - 1.0).abs() < 1e-3, "{sum}");
assert!(b.get(32, 32)[3] < 0.05);
}
#[test]
fn flat_image_stays_flat_with_repeat() {
let img = Image::filled(20, 10, [0.5, 0.5, 0.5, 1.0]);
let b = gaussian_blur(&img, 3.0, 3.0, true);
assert!(b.data.iter().all(|p| (p[0] - 0.5).abs() < 1e-5));
}
#[test]
fn radii_sane() {
let r = box_radii(10.0, 3);
assert_eq!(r.len(), 3);
assert!(r.iter().all(|&v| (7..=10).contains(&v)), "{r:?}");
}
}
+358
View File
@@ -0,0 +1,358 @@
//! Raster images for the compositor.
//!
//! [`Image`] stores premultiplied RGBA in `f32` (values may exceed 1.0 in 32 bpc projects). Every
//! heavy operation is row-parallel with rayon.
pub mod blur;
pub mod warp;
use effectcraft_color::{BlendMode, blend_pixel};
use rayon::prelude::*;
pub use blur::{box_blur, directional_blur, gaussian_blur, radial_blur};
pub use warp::{Sampling, WarpOpts, composite_warp, resample};
pub type Px = [f32; 4];
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Image {
pub width: u32,
pub height: u32,
pub data: Vec<Px>,
}
impl Image {
pub fn new(width: u32, height: u32) -> Image {
Image { width, height, data: vec![[0.0; 4]; width as usize * height as usize] }
}
pub fn filled(width: u32, height: u32, px: Px) -> Image {
Image { width, height, data: vec![px; width as usize * height as usize] }
}
pub fn is_empty(&self) -> bool {
self.width == 0 || self.height == 0
}
#[inline]
pub fn idx(&self, x: u32, y: u32) -> usize {
y as usize * self.width as usize + x as usize
}
#[inline]
pub fn get(&self, x: i64, y: i64) -> Px {
if x < 0 || y < 0 || x >= self.width as i64 || y >= self.height as i64 {
[0.0; 4]
} else {
self.data[y as usize * self.width as usize + x as usize]
}
}
#[inline]
pub fn get_clamped(&self, x: i64, y: i64) -> Px {
let x = x.clamp(0, self.width as i64 - 1);
let y = y.clamp(0, self.height as i64 - 1);
self.data[y as usize * self.width as usize + x as usize]
}
#[inline]
pub fn set(&mut self, x: u32, y: u32, px: Px) {
let i = self.idx(x, y);
self.data[i] = px;
}
pub fn rows_mut(&mut self) -> impl IndexedParallelIterator<Item = (usize, &mut [Px])> {
let w = self.width.max(1) as usize;
self.data.par_chunks_mut(w).enumerate()
}
/// Bilinear sample at continuous pixel coordinates (pixel centres at +0.5); transparent outside.
#[inline]
pub fn sample_bilinear(&self, x: f64, y: f64) -> Px {
let fx = x - 0.5;
let fy = y - 0.5;
let x0 = fx.floor();
let y0 = fy.floor();
let tx = (fx - x0) as f32;
let ty = (fy - y0) as f32;
let (x0, y0) = (x0 as i64, y0 as i64);
let a = self.get(x0, y0);
let b = self.get(x0 + 1, y0);
let c = self.get(x0, y0 + 1);
let d = self.get(x0 + 1, y0 + 1);
let mut o = [0.0; 4];
for i in 0..4 {
let top = a[i] + (b[i] - a[i]) * tx;
let bot = c[i] + (d[i] - c[i]) * tx;
o[i] = top + (bot - top) * ty;
}
o
}
/// Bilinear with edge pixels repeated outside the image.
#[inline]
pub fn sample_bilinear_clamped(&self, x: f64, y: f64) -> Px {
let fx = x - 0.5;
let fy = y - 0.5;
let x0 = fx.floor();
let y0 = fy.floor();
let tx = (fx - x0) as f32;
let ty = (fy - y0) as f32;
let (x0, y0) = (x0 as i64, y0 as i64);
let a = self.get_clamped(x0, y0);
let b = self.get_clamped(x0 + 1, y0);
let c = self.get_clamped(x0, y0 + 1);
let d = self.get_clamped(x0 + 1, y0 + 1);
let mut o = [0.0; 4];
for i in 0..4 {
let top = a[i] + (b[i] - a[i]) * tx;
let bot = c[i] + (d[i] - c[i]) * tx;
o[i] = top + (bot - top) * ty;
}
o
}
/// Catmull-Rom bicubic sample; transparent outside.
pub fn sample_bicubic(&self, x: f64, y: f64) -> Px {
let fx = x - 0.5;
let fy = y - 0.5;
let x0 = fx.floor();
let y0 = fy.floor();
let tx = fx - x0;
let ty = fy - y0;
let w = |t: f64| -> [f32; 4] {
let t2 = t * t;
let t3 = t2 * t;
[
(-0.5 * t3 + t2 - 0.5 * t) as f32,
(1.5 * t3 - 2.5 * t2 + 1.0) as f32,
(-1.5 * t3 + 2.0 * t2 + 0.5 * t) as f32,
(0.5 * t3 - 0.5 * t2) as f32,
]
};
let wx = w(tx);
let wy = w(ty);
let mut o = [0.0f32; 4];
for j in 0..4 {
for i in 0..4 {
let p = self.get(x0 as i64 - 1 + i as i64, y0 as i64 - 1 + j as i64);
let k = wx[i] * wy[j];
for c in 0..4 {
o[c] += p[c] * k;
}
}
}
// Keep premultiplied invariants after ringing.
o[3] = o[3].max(0.0);
for c in 0..3 {
o[c] = o[c].max(0.0);
}
o
}
/// Copy with `pad` transparent pixels on every side.
pub fn padded(&self, pad: u32) -> Image {
let mut out = Image::new(self.width + 2 * pad, self.height + 2 * pad);
let ow = out.width as usize;
for y in 0..self.height as usize {
let src = &self.data[y * self.width as usize..(y + 1) * self.width as usize];
let o = (y + pad as usize) * ow + pad as usize;
out.data[o..o + self.width as usize].copy_from_slice(src);
}
out
}
/// Sub-rectangle copy (clipped).
pub fn crop(&self, x: i64, y: i64, w: u32, h: u32) -> Image {
let mut out = Image::new(w, h);
out.rows_mut().for_each(|(oy, row)| {
for (ox, px) in row.iter_mut().enumerate() {
*px = self.get(x + ox as i64, y + oy as i64);
}
});
out
}
/// Multiply every pixel (premultiplied) by `k`.
pub fn scale_alpha(&mut self, k: f32) {
if (k - 1.0).abs() < 1e-7 {
return;
}
self.data.par_iter_mut().for_each(|p| {
for c in p.iter_mut() {
*c *= k;
}
});
}
/// Multiply each pixel by a coverage value from `mask` (same size).
pub fn mul_mask(&mut self, mask: &[f32]) {
self.data.par_iter_mut().zip(mask.par_iter()).for_each(|(p, &m)| {
for c in p.iter_mut() {
*c *= m;
}
});
}
/// Clamp to [0, 1] (8/16 bpc working space).
pub fn clamp01(&mut self) {
self.data.par_iter_mut().for_each(|p| {
for c in p.iter_mut() {
*c = c.clamp(0.0, 1.0);
}
for c in 0..3 {
p[c] = p[c].min(p[3]);
}
});
}
/// Quantise to `levels` per channel (simulates 8/16 bpc output).
pub fn quantize(&mut self, levels: f32) {
self.data.par_iter_mut().for_each(|p| {
for c in p.iter_mut() {
*c = (*c * levels).round() / levels;
}
});
}
/// Straight-alpha 8-bit RGBA (sRGB-encoded values as stored).
pub fn to_rgba8(&self) -> Vec<u8> {
let mut out = vec![0u8; self.data.len() * 4];
out.par_chunks_mut(4).zip(self.data.par_iter()).for_each(|(o, p)| {
let a = p[3].clamp(0.0, 1.0);
let inv = if a > 0.0 { 1.0 / p[3] } else { 0.0 };
for c in 0..3 {
o[c] = ((p[c] * inv).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
}
o[3] = (a * 255.0 + 0.5) as u8;
});
out
}
/// Composite over an opaque background colour and return opaque 8-bit RGBA.
pub fn to_rgba8_over(&self, bg: [f32; 3]) -> Vec<u8> {
let mut out = vec![0u8; self.data.len() * 4];
out.par_chunks_mut(4).zip(self.data.par_iter()).for_each(|(o, p)| {
let k = 1.0 - p[3].clamp(0.0, 1.0);
for c in 0..3 {
o[c] = ((p[c] + bg[c] * k).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
}
o[3] = 255;
});
out
}
/// From straight-alpha 8-bit RGBA.
pub fn from_rgba8(width: u32, height: u32, rgba: &[u8]) -> Image {
let mut img = Image::new(width, height);
img.data.par_iter_mut().zip(rgba.par_chunks(4)).for_each(|(p, s)| {
let a = s[3] as f32 / 255.0;
*p = [s[0] as f32 / 255.0 * a, s[1] as f32 / 255.0 * a, s[2] as f32 / 255.0 * a, a];
});
img
}
/// Straight-alpha colour at a pixel.
pub fn straight(&self, x: i64, y: i64) -> Px {
let p = self.get(x, y);
if p[3] > 0.0 { [p[0] / p[3], p[1] / p[3], p[2] / p[3], p[3]] } else { [0.0; 4] }
}
/// Map every pixel through `f` on straight colour (keeps alpha).
pub fn map_straight(&mut self, f: impl Fn([f32; 3]) -> [f32; 3] + Sync) {
self.data.par_iter_mut().for_each(|p| {
let a = p[3];
if a <= 0.0 {
return;
}
let c = f([p[0] / a, p[1] / a, p[2] / a]);
*p = [c[0] * a, c[1] * a, c[2] * a, a];
});
}
/// Blend `src` (same size) onto self with a mode and opacity.
pub fn blend_from(&mut self, src: &Image, mode: BlendMode, opacity: f32, seed: u32) {
let w = self.width as usize;
self.data.par_chunks_mut(w.max(1)).zip(src.data.par_chunks(w.max(1))).enumerate().for_each(|(y, (d, s))| {
for x in 0..d.len() {
let mut sp = s[x];
if sp[3] <= 0.0 && !mode.is_stencil() {
continue;
}
for c in sp.iter_mut() {
*c *= opacity;
}
let n = if matches!(mode, BlendMode::Dissolve | BlendMode::DancingDissolve) { hash_noise(x as u32, y as u32, seed) } else { 0.5 };
d[x] = blend_pixel(mode, d[x], sp, n);
}
});
}
/// Bounding box of non-transparent pixels (x0, y0, x1, y1), None if empty.
pub fn alpha_bounds(&self) -> Option<(u32, u32, u32, u32)> {
let w = self.width as usize;
let mut b: Option<(u32, u32, u32, u32)> = None;
for (y, row) in self.data.chunks(w.max(1)).enumerate() {
if let Some(first) = row.iter().position(|p| p[3] > 1e-6) {
let last = row.iter().rposition(|p| p[3] > 1e-6).unwrap_or(first);
let (y, f, l) = (y as u32, first as u32, last as u32 + 1);
b = Some(match b {
None => (f, y, l, y + 1),
Some((x0, y0, x1, _)) => (x0.min(f), y0, x1.max(l), y + 1),
});
}
}
b
}
}
/// Deterministic per-pixel noise in 0..1.
#[inline]
pub fn hash_noise(x: u32, y: u32, seed: u32) -> f32 {
let mut h = x.wrapping_mul(0x8da6_b343) ^ y.wrapping_mul(0xd816_3841) ^ seed.wrapping_mul(0xcb1a_b31f);
h ^= h >> 13;
h = h.wrapping_mul(0x5bd1_e995);
h ^= h >> 15;
(h & 0x00ff_ffff) as f32 / 16_777_216.0
}
/// A single-channel coverage mask.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Mask {
pub width: u32,
pub height: u32,
pub data: Vec<f32>,
}
impl Mask {
pub fn new(width: u32, height: u32, v: f32) -> Mask {
Mask { width, height, data: vec![v; width as usize * height as usize] }
}
pub fn to_image(&self) -> Image {
Image { width: self.width, height: self.height, data: self.data.iter().map(|&a| [a, a, a, a]).collect() }
}
pub fn from_alpha(img: &Image) -> Mask {
Mask { width: img.width, height: img.height, data: img.data.iter().map(|p| p[3]).collect() }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rgba8_roundtrip() {
let src: Vec<u8> = vec![255, 128, 0, 255, 10, 20, 30, 128, 0, 0, 0, 0, 1, 2, 3, 4];
let img = Image::from_rgba8(2, 2, &src);
let back = img.to_rgba8();
for (a, b) in src.chunks(4).zip(back.chunks(4)) {
if a[3] >= 128 {
assert!(a.iter().zip(b).all(|(x, y)| (*x as i32 - *y as i32).abs() <= 1), "{a:?} {b:?}");
} else {
assert!((a[3] as i32 - b[3] as i32).abs() <= 1);
}
}
}
#[test]
fn bilinear_at_centres_is_exact() {
let mut img = Image::new(3, 3);
img.set(1, 1, [0.5, 0.25, 0.125, 1.0]);
assert_eq!(img.sample_bilinear(1.5, 1.5), [0.5, 0.25, 0.125, 1.0]);
let half = img.sample_bilinear(2.0, 1.5);
assert!((half[3] - 0.5).abs() < 1e-6);
}
#[test]
fn alpha_bounds_found() {
let mut img = Image::new(10, 10);
img.set(3, 4, [1.0; 4]);
img.set(6, 7, [1.0; 4]);
assert_eq!(img.alpha_bounds(), Some((3, 4, 7, 8)));
}
#[test]
fn noise_in_range() {
for i in 0..1000 {
let n = hash_noise(i, i * 7, 3);
assert!((0.0..1.0).contains(&n));
}
}
}
+182
View File
@@ -0,0 +1,182 @@
//! Projective warps composited straight into a destination (the layer transform step).
use effectcraft_color::{BlendMode, blend_pixel};
use effectcraft_geom::{Mat3, Rect, vec2};
use rayon::prelude::*;
use crate::{Image, hash_noise};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Sampling {
Nearest,
#[default]
Bilinear,
Bicubic,
}
#[derive(Clone, Copy, Debug)]
pub struct WarpOpts {
pub sampling: Sampling,
pub opacity: f32,
pub mode: BlendMode,
pub seed: u32,
/// Only touch destination pixels inside this rect (dst pixel coords).
pub clip: Option<Rect>,
}
impl Default for WarpOpts {
fn default() -> Self {
WarpOpts { sampling: Sampling::Bilinear, opacity: 1.0, mode: BlendMode::Normal, seed: 0, clip: None }
}
}
/// Box-filter halving (for minification).
fn half(src: &Image) -> Image {
let w = src.width.div_ceil(2).max(1);
let h = src.height.div_ceil(2).max(1);
let mut out = Image::new(w, h);
out.rows_mut().for_each(|(y, row)| {
for (x, px) in row.iter_mut().enumerate() {
let (sx, sy) = (2 * x as i64, 2 * y as i64);
let mut acc = [0.0f32; 4];
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
let p = src.get_clamped(sx + dx, sy + dy);
for c in 0..4 {
acc[c] += p[c];
}
}
*px = acc.map(|v| v * 0.25);
}
});
out
}
/// Draw `src` transformed by `m` (src pixel space → dst pixel space) onto `dst` with blending.
pub fn composite_warp(dst: &mut Image, src: &Image, m: &Mat3, opts: &WarpOpts) {
if src.is_empty() || dst.is_empty() || opts.opacity <= 0.0 {
return;
}
let Some(inv) = m.inverse() else { return };
// Minification: pick a pre-filtered level so sampling doesn't alias.
let scale = m.mean_scale();
let mut level_img;
let mut img = src;
let mut inv = inv;
if scale < 0.5 && m.is_affine() {
let mut s = scale;
let mut f = 1.0;
level_img = half(src);
f *= 0.5;
s *= 2.0;
while s < 0.5 && level_img.width > 1 && level_img.height > 1 {
level_img = half(&level_img);
f *= 0.5;
s *= 2.0;
}
img = &level_img;
inv = Mat3::scale(vec2(f, f)) * inv;
}
let bounds = m.map_rect(&Rect::from_size(src.width as f64, src.height as f64)).inflate(1.0).round_out();
let full = Rect::from_size(dst.width as f64, dst.height as f64);
let mut area = bounds.intersect(&full);
if let Some(c) = opts.clip {
area = area.intersect(&c);
}
if area.is_empty() {
return;
}
let (x0, x1) = (area.x0.max(0.0) as usize, area.x1.min(dst.width as f64) as usize);
let (y0, y1) = (area.y0.max(0.0) as usize, area.y1.min(dst.height as f64) as usize);
let w = dst.width as usize;
let affine = inv.is_affine();
let mode = opts.mode;
let op = opts.opacity;
dst.data.par_chunks_mut(w).enumerate().skip(y0).take(y1 - y0).for_each(|(y, row)| {
let fy = y as f64 + 0.5;
let mut sp = inv.apply(vec2(x0 as f64 + 0.5, fy));
let step = inv.apply_vec(vec2(1.0, 0.0));
for x in x0..x1 {
let p = if affine {
let p = sp;
sp += step;
p
} else {
inv.apply(vec2(x as f64 + 0.5, fy))
};
if p.x < -1.0 || p.y < -1.0 || p.x > img.width as f64 + 1.0 || p.y > img.height as f64 + 1.0 {
if mode.is_stencil() {
row[x] = blend_pixel(mode, row[x], [0.0; 4], 0.5);
}
continue;
}
let mut s = match opts.sampling {
Sampling::Nearest => img.get(p.x.floor() as i64, p.y.floor() as i64),
Sampling::Bilinear => img.sample_bilinear(p.x, p.y),
Sampling::Bicubic => img.sample_bicubic(p.x, p.y),
};
if s[3] <= 0.0 && !mode.is_stencil() {
continue;
}
if op < 1.0 {
for c in s.iter_mut() {
*c *= op;
}
}
let n = if matches!(mode, BlendMode::Dissolve | BlendMode::DancingDissolve) { hash_noise(x as u32, y as u32, opts.seed) } else { 0.5 };
row[x] = blend_pixel(mode, row[x], s, n);
}
});
// Stencil modes also clear everything outside the layer bounds.
if mode.is_stencil() && matches!(mode, BlendMode::StencilAlpha | BlendMode::StencilLuma) {
for (y, row) in dst.data.chunks_mut(w).enumerate() {
for (x, px) in row.iter_mut().enumerate() {
if x < x0 || x >= x1 || y < y0 || y >= y1 {
*px = [0.0; 4];
}
}
}
}
}
/// Resize with bilinear filtering (box pre-filter when shrinking).
pub fn resample(src: &Image, w: u32, h: u32) -> Image {
let mut out = Image::new(w, h);
if src.is_empty() || w == 0 || h == 0 {
return out;
}
let m = Mat3::scale(vec2(w as f64 / src.width as f64, h as f64 / src.height as f64));
composite_warp(&mut out, src, &m, &WarpOpts::default());
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn identity_warp_copies() {
let mut src = Image::new(4, 4);
src.set(1, 2, [0.5, 0.5, 0.5, 1.0]);
let mut dst = Image::new(4, 4);
composite_warp(&mut dst, &src, &Mat3::IDENTITY, &WarpOpts::default());
assert_eq!(dst.get(1, 2), [0.5, 0.5, 0.5, 1.0]);
assert_eq!(dst.get(0, 0), [0.0; 4]);
}
#[test]
fn translate_by_integer() {
let mut src = Image::new(4, 4);
src.set(0, 0, [1.0; 4]);
let mut dst = Image::new(8, 8);
composite_warp(&mut dst, &src, &Mat3::translate(vec2(3.0, 2.0)), &WarpOpts::default());
assert_eq!(dst.get(3, 2), [1.0; 4]);
}
#[test]
fn downscale_preserves_average() {
let src = Image::filled(64, 64, [0.25, 0.5, 0.75, 1.0]);
let out = resample(&src, 8, 8);
let p = out.get(4, 4);
assert!((p[1] - 0.5).abs() < 1e-4 && (p[3] - 1.0).abs() < 1e-4, "{p:?}");
}
}