PhotoCraft: An open-source, photo editor written by scratch in pure Rust
perf(panorama): Photomerge 4× faster, bit for bit the same (#6489)
Nicolas Falesy5f65579ecb44
diff --git a/crates/algo/src/features.rs b/crates/algo/src/features.rsindex ab98de757..e8e45bcaf 100644--- a/crates/algo/src/features.rs+++ b/crates/algo/src/features.rs@@ -60,25 +60,98 @@ impl Rng {}}+/// Columns per band of the vertical blur pass: 64 f32 = 256 bytes = four cache lines per row, so+/// walking down a band touches whole lines, and the band's working set stays in cache.+const BLUR_BAND: usize = 64;++/// Box blur of radius `r` (edges clamped): a running f32 sum along rows, then along columns.+///+/// Both passes are parallel and give bit for bit what the one-line-at-a-time version gave: every+/// output sums its window in the same order. Rows are independent. For the column pass, the+/// image is cut into bands of columns; each column keeps its own f32 running sum, started from+/// its first window summed in order and updated in the same order, so only the loop nest changes+/// (the inner loop runs across a band's columns and vectorises), never any column's arithmetic.fn blur(w: usize, h: usize, v: &[f32], r: usize) -> Vec<f32> {- let pass = |src: &[f32], horizontal: bool| -> Vec<f32> {- let mut dst = vec![0.0f32; src.len()];- let (n, m) = if horizontal { (h, w) } else { (w, h) };- for line in 0..n {- let at = |k: i64| {- let k = k.clamp(0, m as i64 - 1) as usize;- if horizontal { src[line * w + k] } else { src[k * w + line] }- };- let mut acc: f32 = (-(r as i64)..=r as i64).map(at).sum();- for k in 0..m {- let i = if horizontal { line * w + k } else { k * w + line };- dst[i] = acc / (2 * r + 1) as f32;- acc += at(k as i64 + r as i64 + 1) - at(k as i64 - r as i64);+ if w == 0 || h == 0 {+ return Vec::new();+ }+ let den = (2 * r + 1) as f32;+ let mut tmp = vec![0.0f32; w * h];+ par_rows(&mut tmp, w, |line, dst| {+ let src = &v[line * w..(line + 1) * w];+ let at = |k: i64| src[k.clamp(0, w as i64 - 1) as usize];+ let mut acc: f32 = (-(r as i64)..=r as i64).map(at).sum();+ for (k, o) in dst.iter_mut().enumerate() {+ *o = acc / den;+ acc += at(k as i64 + r as i64 + 1) - at(k as i64 - r as i64);+ }+ });+ let mut dst = vec![0.0f32; w * h];+ // One list of row segments per band, each segment a `&mut` slice of `dst`: no `unsafe`.+ let mut bands: Vec<Vec<&mut [f32]>> = (0..w.div_ceil(BLUR_BAND)).map(|_| Vec::with_capacity(h)).collect();+ for row in dst.chunks_exact_mut(w) {+ for (band, seg) in bands.iter_mut().zip(row.chunks_mut(BLUR_BAND)) {+ band.push(seg);+ }+ }+ let src = &tmp;+ let run = |bi: usize, segs: &mut [&mut [f32]], acc: &mut Vec<f32>| {+ let (x0, bw) = (bi * BLUR_BAND, segs.first().map_or(0, |s| s.len()));+ let row = |k: i64| {+ let o = (k.clamp(0, h as i64 - 1) as usize) * w + x0;+ &src[o..o + bw]+ };+ // The first window, summed in order from the same start as `Iterator::sum` uses.+ acc.clear();+ acc.resize(bw, std::iter::empty::<f32>().sum());+ for k in -(r as i64)..=r as i64 {+ for (t, &x) in acc.iter_mut().zip(row(k)) {+ *t += x;+ }+ }+ for (k, seg) in segs.iter_mut().enumerate() {+ let (add, sub) = (row(k as i64 + r as i64 + 1), row(k as i64 - r as i64));+ for (((o, t), &p), &m) in seg.iter_mut().zip(acc.iter_mut()).zip(add).zip(sub) {+ *o = *t / den;+ *t += p - m;}}- dst};- pass(&pass(v, true), false)+ #[cfg(not(target_arch = "wasm32"))]+ {+ use rayon::prelude::*;+ bands.into_par_iter().enumerate().for_each_init(Vec::new, |acc, (bi, mut segs)| run(bi, &mut segs, acc));+ }+ #[cfg(target_arch = "wasm32")]+ {+ let mut acc = Vec::new();+ for (bi, mut segs) in bands.into_iter().enumerate() {+ run(bi, &mut segs, &mut acc);+ }+ }+ dst+}++/// Runs `f(y, row)` over the `w`-wide rows of `buf`, in parallel on native targets.+fn par_rows(buf: &mut [f32], w: usize, f: impl Fn(usize, &mut [f32]) + Sync + Send) {+ #[cfg(not(target_arch = "wasm32"))]+ {+ use rayon::prelude::*;+ buf.par_chunks_mut(w).enumerate().for_each(|(y, row)| f(y, row));+ }+ #[cfg(target_arch = "wasm32")]+ buf.chunks_mut(w).enumerate().for_each(|(y, row)| f(y, row));+}++/// [`par_rows`] over three row-aligned buffers in lockstep.+fn par_rows3(a: &mut [f32], b: &mut [f32], c: &mut [f32], w: usize, f: impl Fn(usize, &mut [f32], &mut [f32], &mut [f32]) + Sync + Send) {+ #[cfg(not(target_arch = "wasm32"))]+ {+ use rayon::prelude::*;+ a.par_chunks_mut(w).zip(b.par_chunks_mut(w)).zip(c.par_chunks_mut(w)).enumerate().for_each(|(y, ((a, b), c))| f(y, a, b, c));+ }+ #[cfg(target_arch = "wasm32")]+ a.chunks_mut(w).zip(b.chunks_mut(w)).zip(c.chunks_mut(w)).enumerate().for_each(|(y, ((a, b), c))| f(y, a, b, c));}/// Harris corners: at most `max` corners at least `min_dist` pixels apart, strongest first,@@ -88,28 +161,40 @@ pub fn harris(w: usize, h: usize, img: &[f32], max: usize, min_dist: f32, valid:return Vec::new();}let (mut xx, mut yy, mut xy) = (vec![0.0f32; w * h], vec![0.0f32; w * h], vec![0.0f32; w * h]);- for y in 1..h - 1 {+ // Rows are independent (each output pixel reads only `img`), so they run in parallel.+ par_rows3(&mut xx, &mut yy, &mut xy, w, |y, xxr, yyr, xyr| {+ if y == 0 || y + 1 == h {+ return;+ }for x in 1..w - 1 {let p = |dx: i64, dy: i64| img[((y as i64 + dy) as usize) * w + (x as i64 + dx) as usize];// Sobel.let gx = (p(1, -1) + 2.0 * p(1, 0) + p(1, 1)) - (p(-1, -1) + 2.0 * p(-1, 0) + p(-1, 1));let gy = (p(-1, 1) + 2.0 * p(0, 1) + p(1, 1)) - (p(-1, -1) + 2.0 * p(0, -1) + p(1, -1));- let i = y * w + x;- xx[i] = gx * gx;- yy[i] = gy * gy;- xy[i] = gx * gy;+ xxr[x] = gx * gx;+ yyr[x] = gy * gy;+ xyr[x] = gx * gy;}- }+ });// Two box passes approximate the Gaussian window.let (xx, yy, xy) = (blur(w, h, &blur(w, h, &xx, 1), 1), blur(w, h, &blur(w, h, &yy, 1), 1), blur(w, h, &blur(w, h, &xy, 1), 1));- let r: Vec<f32> = (0..w * h).map(|i| xx[i] * yy[i] - xy[i] * xy[i] - 0.04 * (xx[i] + yy[i]).powi(2)).collect();+ let mut r = vec![0.0f32; w * h];+ par_rows(&mut r, w, |y, row| {+ for (x, o) in row.iter_mut().enumerate() {+ let i = y * w + x;+ *o = xx[i] * yy[i] - xy[i] * xy[i] - 0.04 * (xx[i] + yy[i]).powi(2);+ }+ });let peak = r.iter().copied().fold(0.0f32, f32::max);if peak <= 0.0 {return Vec::new();}let m = PATCH_RADIUS + 1;- let mut cand: Vec<Corner> = Vec::new();- for y in m..h - m {+ // Rows are scanned in parallel and joined in row order; the sort below fully orders the+ // candidates anyway (score, then y, then x), so the order they arrive in cannot matter.+ let rows = par_map((h - m).saturating_sub(m), |i| {+ let y = m + i;+ let mut found: Vec<Corner> = Vec::new();for x in m..w - m {let v = r[y * w + x];if v < peak * 0.01 {@@ -125,9 +210,11 @@ pub fn harris(w: usize, h: usize, img: &[f32], max: usize, min_dist: f32, valid:continue;}}- cand.push(Corner { x: x as f32, y: y as f32, score: v });+ found.push(Corner { x: x as f32, y: y as f32, score: v });}- }+ found+ });+ let mut cand: Vec<Corner> = rows.into_iter().flatten().collect();cand.sort_by(|a, b| b.score.total_cmp(&a.score).then(a.y.total_cmp(&b.y)).then(a.x.total_cmp(&b.x)));// Minimum spacing via a coarse occupancy grid.let cell = min_dist.max(1.0);@@ -176,37 +263,37 @@ pub fn describe(w: usize, h: usize, img: &[f32], corners: &[Corner], upright: bolet (xi, yi) = ((x.round() as i64).clamp(0, w as i64 - 1) as usize, (y.round() as i64).clamp(0, h as i64 - 1) as usize);smooth[yi * w + xi]};- corners- .iter()- .map(|c| {- let (s, co) = if upright {- (0.0, 1.0)- } else {- let (mut m10, mut m01) = (0.0f32, 0.0f32);- let r = PATCH_RADIUS as i64;- for dy in -r..=r {- for dx in -r..=r {- if dx * dx + dy * dy <= r * r {- let v = at(c.x + dx as f32, c.y + dy as f32);- m10 += dx as f32 * v;- m01 += dy as f32 * v;- }+ // Every descriptor depends only on its own corner and the smoothed image: computed in+ // parallel, kept in corner order.+ par_map(corners.len(), |ci| {+ let c = &corners[ci];+ let (s, co) = if upright {+ (0.0, 1.0)+ } else {+ let (mut m10, mut m01) = (0.0f32, 0.0f32);+ let r = PATCH_RADIUS as i64;+ for dy in -r..=r {+ for dx in -r..=r {+ if dx * dx + dy * dy <= r * r {+ let v = at(c.x + dx as f32, c.y + dy as f32);+ m10 += dx as f32 * v;+ m01 += dy as f32 * v;}}- m01.atan2(m10).sin_cos()- };- let mut d = [0u64; 4];- for (i, p) in pairs().iter().enumerate() {- let rot = |x: f32, y: f32| (c.x + x * co - y * s, c.y + x * s + y * co);- let (ax, ay) = rot(p[0], p[1]);- let (bx, by) = rot(p[2], p[3]);- if at(ax, ay) < at(bx, by) {- d[i / 64] |= 1 << (i % 64);- }}- d- })- .collect()+ m01.atan2(m10).sin_cos()+ };+ let mut d = [0u64; 4];+ for (i, p) in pairs().iter().enumerate() {+ let rot = |x: f32, y: f32| (c.x + x * co - y * s, c.y + x * s + y * co);+ let (ax, ay) = rot(p[0], p[1]);+ let (bx, by) = rot(p[2], p[3]);+ if at(ax, ay) < at(bx, by) {+ d[i / 64] |= 1 << (i % 64);+ }+ }+ d+ })}pub fn hamming(a: &Descriptor, b: &Descriptor) -> u32 {@@ -560,3 +647,121 @@ mod tests {assert_eq!(hamming(&[0, 0, 0, 0], &[1, 3, 0, u64::MAX]), 67);}}++/// The row / column-band parallel `blur`, `harris` and `describe` against the serial code they+/// replaced. Every output must stay bit for bit the same.+#[cfg(test)]+mod parallel_tests {+ use super::*;++ /// The serial blur exactly as it was before the parallelisation.+ fn ref_blur(w: usize, h: usize, v: &[f32], r: usize) -> Vec<f32> {+ let pass = |src: &[f32], horizontal: bool| -> Vec<f32> {+ let mut dst = vec![0.0f32; src.len()];+ let (n, m) = if horizontal { (h, w) } else { (w, h) };+ for line in 0..n {+ let at = |k: i64| {+ let k = k.clamp(0, m as i64 - 1) as usize;+ if horizontal { src[line * w + k] } else { src[k * w + line] }+ };+ let mut acc: f32 = (-(r as i64)..=r as i64).map(at).sum();+ for k in 0..m {+ let i = if horizontal { line * w + k } else { k * w + line };+ dst[i] = acc / (2 * r + 1) as f32;+ acc += at(k as i64 + r as i64 + 1) - at(k as i64 - r as i64);+ }+ }+ dst+ };+ pass(&pass(v, true), false)+ }++ fn mix(mut z: u64) -> u64 {+ z = z.wrapping_add(0x9E37_79B9_7F4A_7C15);+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);+ z ^ (z >> 31)+ }++ /// Integer-only data with negatives, signed zeros and large values, so a different order of+ /// additions cannot hide.+ fn noise(len: usize, seed: u64) -> Vec<f32> {+ (0..len as u64)+ .map(|i| {+ let z = mix(seed.wrapping_mul(0x1234_5678_9ABC).wrapping_add(i));+ let v = (z >> 40) as f32 / 16_777_216.0;+ match z & 31 {+ 0 => -v,+ 1 => -0.0,+ 2 => v * 1000.0,+ _ => v,+ }+ })+ .collect()+ }++ /// Blocks of random brightness: lots of strong corners, no libm in the making.+ fn blocks(w: usize, h: usize, seed: u64) -> Vec<f32> {+ (0..w * h).map(|i| (mix(seed + ((i % w) / 8) as u64 * 4096 + ((i / w) / 8) as u64) >> 40) as f32 / 16_777_216.0).collect()+ }++ fn fnv(parts: &[u64]) -> u64 {+ let mut h = 0xcbf2_9ce4_8422_2325u64;+ for p in parts {+ h ^= p;+ h = h.wrapping_mul(0x0000_0100_0000_01b3);+ }+ h+ }++ #[test]+ fn blur_matches_the_serial_code() {+ // Widths around the 64-column band (1 band, band + 1, several bands, a ragged last one),+ // 1-wide and 1-high images, and radii 0, 1, 2, larger than the image.+ let widths = [1usize, 2, 3, 31, 63, 64, 65, 127, 128, 129, 200];+ let heights = [1usize, 2, 3, 5, 17, 40];+ for (a, &w) in widths.iter().enumerate() {+ for (b, &h) in heights.iter().enumerate() {+ let v = noise(w * h, (a * 10 + b) as u64);+ for r in [0usize, 1, 2, 3, 7, 50] {+ let (got, want) = (blur(w, h, &v, r), ref_blur(w, h, &v, r));+ let (g, e): (Vec<u32>, Vec<u32>) = (got.iter().map(|x| x.to_bits()).collect(), want.iter().map(|x| x.to_bits()).collect());+ assert_eq!(g, e, "blur {w}x{h} r={r}");+ }+ }+ }+ assert!(blur(0, 0, &[], 1).is_empty());+ }++ // `harris` and `describe` go through the platform's hypot / ln / cos / atan2 / sin_cos, so the+ // hashes recorded from the old code only hold where those are the same functions.+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]+ #[test]+ fn harris_and_describe_hashes_recorded_from_the_serial_code() {+ // Sizes: a whole number of 64-column bands and a ragged one; with and without a validity mask.+ for (w, h, max, md, want_corners, want_desc) in+ [(211usize, 157usize, 300usize, 6.0f32, 0xeccc6928d3ae3b8cu64, 0xd1e6caae4d68f253u64), (128, 97, 60, 3.0, 0xe3f6615117fa7da7, 0x818ae7e965ecf88f)]+ {+ let img = blocks(w, h, 7);+ let valid: Vec<bool> = (0..w * h).map(|i| !((i % w) > w / 2 && (i / w) < h / 3)).collect();+ let mut parts = Vec::new();+ for v in [None, Some(valid.as_slice())] {+ let c = harris(w, h, &img, max, md, v);+ for k in &c {+ parts.extend([k.x.to_bits() as u64, k.y.to_bits() as u64, k.score.to_bits() as u64]);+ }+ parts.push(c.len() as u64);+ }+ assert_eq!(fnv(&parts), want_corners, "harris {w}x{h}");+ let c = harris(w, h, &img, max, md, None);+ assert!(c.len() > 10, "{} corners", c.len());+ let mut parts = Vec::new();+ for upright in [false, true] {+ for d in describe(w, h, &img, &c, upright) {+ parts.extend(d);+ }+ }+ assert_eq!(fnv(&parts), want_desc, "describe {w}x{h}");+ }+ }+}diff --git a/crates/algo/src/panorama.rs b/crates/algo/src/panorama.rsindex fd7ccbc59..abe17db39 100644--- a/crates/algo/src/panorama.rs+++ b/crates/algo/src/panorama.rs@@ -35,7 +35,7 @@#![allow(clippy::needless_range_loop)] // index loops mirror the maths (pixels × channels)use crate::features::{self, Descriptor, Model};-use crate::photo_util::{Normal, Rng, par_map, solve_dense};+use crate::photo_util::{Normal, Rng, par_map, par_rows, solve_dense};use crate::transform::Homography;/// Photomerge layouts.@@ -996,58 +996,99 @@ pub fn blend_levels(w: usize, h: usize) -> usize {n}+/// `a[i] ⊕ b[i]` for every `i` (the shorter length wins, like `zip`), in parallel on native+/// targets. Purely elementwise, so the result is the serial result bit for bit.+fn par_zip(a: &[f32], b: &[f32], f: impl Fn(f32, f32) -> f32 + Sync + Send) -> Vec<f32> {+ const CHUNK: usize = 1 << 14;+ let mut out = vec![0.0f32; a.len().min(b.len())];+ let fill = |o: &mut [f32], a: &[f32], b: &[f32]| {+ for ((o, &a), &b) in o.iter_mut().zip(a).zip(b) {+ *o = f(a, b);+ }+ };+ #[cfg(not(target_arch = "wasm32"))]+ {+ use rayon::prelude::*;+ out.par_chunks_mut(CHUNK).zip(a.par_chunks(CHUNK)).zip(b.par_chunks(CHUNK)).for_each(|((o, a), b)| fill(o, a, b));+ }+ #[cfg(target_arch = "wasm32")]+ out.chunks_mut(CHUNK).zip(a.chunks(CHUNK)).zip(b.chunks(CHUNK)).for_each(|((o, a), b)| fill(o, a, b));+ out+}++/// `f(a[i])` for every `i`, in parallel on native targets (elementwise, so bit for bit serial).+fn par_map1(a: &[f32], f: impl Fn(f32) -> f32 + Sync + Send) -> Vec<f32> {+ par_zip(a, a, |x, _| f(x))+}++// `reduce`, `expand` and `push_pull` run one pyramid level for one image at a time, and the+// images themselves only fill part of a many-core machine, so each of them also runs its rows+// in parallel. Every output element is computed by the same expression, in the same order, as+// the one-thread loops they replace (rows never read each other's output), so the result is+// bit for bit unchanged.+fn reduce(w: usize, h: usize, ch: usize, src: &[f32]) -> (usize, usize, Vec<f32>) {let (nw, nh) = (w.div_ceil(2), h.div_ceil(2));let k = [1.0f32, 4.0, 6.0, 4.0, 1.0];// Separable 5-tap binomial, then decimate.let mut tmp = vec![0.0f32; nw * h * ch];- for y in 0..h {+ par_rows(&mut tmp, nw, ch, |y, row| {+ let line = &src[y * w * ch..(y + 1) * w * ch];for x in 0..nw {+ // The clamped source column of each tap is the same for every channel.+ let xs: [usize; 5] = std::array::from_fn(|t| (2 * x as i64 + t as i64 - 2).clamp(0, w as i64 - 1) as usize * ch);for c in 0..ch {let mut s = 0.0;- for (t, kv) in k.iter().enumerate() {- let xx = (2 * x as i64 + t as i64 - 2).clamp(0, w as i64 - 1) as usize;- s += kv * src[(y * w + xx) * ch + c];+ for (kv, xx) in k.iter().zip(xs) {+ s += kv * line[xx + c];}- tmp[(y * nw + x) * ch + c] = s / 16.0;+ row[x * ch + c] = s / 16.0;}}- }+ });let mut out = vec![0.0f32; nw * nh * ch];- for y in 0..nh {- for x in 0..nw {- for c in 0..ch {- let mut s = 0.0;- for (t, kv) in k.iter().enumerate() {- let yy = (2 * y as i64 + t as i64 - 2).clamp(0, h as i64 - 1) as usize;- s += kv * tmp[(yy * nw + x) * ch + c];- }- out[(y * nw + x) * ch + c] = s / 16.0;+ par_rows(&mut out, nw, ch, |y, row| {+ // Each output row is five source rows added in tap order: the same sum per element as+ // before (`0 + k0·a + k1·b + …`), but over whole rows so it vectorises.+ for (t, kv) in k.iter().enumerate() {+ let yy = (2 * y as i64 + t as i64 - 2).clamp(0, h as i64 - 1) as usize;+ for (o, &v) in row.iter_mut().zip(&tmp[yy * nw * ch..(yy + 1) * nw * ch]) {+ *o += kv * v;}}- }+ for o in row.iter_mut() {+ *o /= 16.0;+ }+ });(nw, nh, out)}fn expand(sw: usize, sh: usize, ch: usize, src: &[f32], w: usize, h: usize) -> Vec<f32> {// Bilinear upsampling at half-pixel-aligned positions.let mut out = vec![0.0f32; w * h * ch];- for y in 0..h {+ // Source columns and weights depend on x only: worked out once instead of for every row.+ // The clamped position is never negative, so truncating is `floor` (and spares the libm call).+ let cols: Vec<(usize, usize, f32)> = (0..w)+ .map(|x| {+ let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sw - 1) as f32);+ let x0 = fx as usize;+ (x0 * ch, (x0 + 1).min(sw - 1) * ch, fx - x0 as f32)+ })+ .collect();+ par_rows(&mut out, w, ch, |y, row| {let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sh - 1) as f32);- let (y0, ty) = (fy.floor() as usize, fy - fy.floor());+ let y0 = fy as usize;+ let ty = fy - y0 as f32;let y1 = (y0 + 1).min(sh - 1);- for x in 0..w {- let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sw - 1) as f32);- let (x0, tx) = (fx.floor() as usize, fx - fx.floor());- let x1 = (x0 + 1).min(sw - 1);- for c in 0..ch {- let p = |xx: usize, yy: usize| src[(yy * sw + xx) * ch + c];- let top = p(x0, y0) + (p(x1, y0) - p(x0, y0)) * tx;- let bot = p(x0, y1) + (p(x1, y1) - p(x0, y1)) * tx;- out[(y * w + x) * ch + c] = top + (bot - top) * ty;+ let (r0, r1) = (&src[y0 * sw * ch..(y0 + 1) * sw * ch], &src[y1 * sw * ch..(y1 + 1) * sw * ch]);+ for (px, &(x0, x1, tx)) in row.chunks_exact_mut(ch.max(1)).zip(&cols) {+ for (c, o) in px.iter_mut().enumerate() {+ let top = r0[x0 + c] + (r0[x1 + c] - r0[x0 + c]) * tx;+ let bot = r1[x0 + c] + (r1[x1 + c] - r1[x0 + c]) * tx;+ *o = top + (bot - top) * ty;}}- }+ });out}@@ -1058,41 +1099,75 @@ fn push_pull(w: usize, h: usize, ch: usize, px: &mut [f32], wt: &[f32]) {return;}let (nw, nh) = (w.div_ceil(2), h.div_ceil(2));+ // Coarse sums. A coarse row is fed by two fine rows; walking them in raster order adds each+ // coarse cell's (up to) four fine pixels in the order the serial scatter-add did, from zero.let mut cpx = vec![0.0f32; nw * nh * ch];let mut cw = vec![0.0f32; nw * nh];- for y in 0..h {- for x in 0..w {- let (i, j) = (y * w + x, (y / 2) * nw + x / 2);- let a = wt[i];- cw[j] += a;- for c in 0..ch {- cpx[j * ch + c] += a * px[i * ch + c];+ par_rows(&mut cw, nw, 1, |cy, row| {+ for y in 2 * cy..(2 * cy + 2).min(h) {+ for (x, &a) in wt[y * w..(y + 1) * w].iter().enumerate() {+ row[x / 2] += a;}}- }- for j in 0..nw * nh {- if cw[j] > 0.0 {- for c in 0..ch {- cpx[j * ch + c] /= cw[j];+ });+ let px_in: &[f32] = px;+ par_rows(&mut cpx, nw, ch, |cy, row| {+ for y in 2 * cy..(2 * cy + 2).min(h) {+ for x in 0..w {+ let (i, j) = (y * w + x, x / 2);+ let a = wt[i];+ for c in 0..ch {+ row[j * ch + c] += a * px_in[i * ch + c];+ }+ }+ }+ });+ // Normalise by the weight (this reads `cw` before it is reset to 0 / 1 below).+ par_rows(&mut cpx, nw, ch, |cy, row| {+ for cx in 0..nw {+ let wj = cw[cy * nw + cx];+ if wj > 0.0 {+ for c in 0..ch {+ row[cx * ch + c] /= wj;+ }}- cw[j] = 1.0;+ }+ });+ for v in cw.iter_mut() {+ if *v > 0.0 {+ *v = 1.0;}}if cw.contains(&0.0) && cw.iter().any(|v| *v > 0.0) {push_pull(nw, nh, ch, &mut cpx, &cw);}- for y in 0..h {+ par_rows(px, w, ch, |y, row| {for x in 0..w {let i = y * w + x;if wt[i] < 1.0 {let j = (y / 2) * nw + x / 2;let a = wt[i];for c in 0..ch {- px[i * ch + c] = a * px[i * ch + c] + (1.0 - a) * cpx[j * ch + c];+ row[x * ch + c] = a * row[x * ch + c] + (1.0 - a) * cpx[j * ch + c];}}}- }+ });+}++/// One image's pyramid in [`multiband`]: the grid origin `(gx0, gy0)` at level 0, the Laplacian+/// levels `(w, h, colours)` and the Gaussian weight levels.+type PyramidBand = (i32, i32, Vec<(usize, usize, Vec<f32>)>, Vec<Vec<f32>>);++/// The part of `band` on panorama row `py` of level `l`: the panorama column its first pixel+/// lands on, its width, its weight row and its colour row. `None` when it misses the row.+fn band_row(band: &PyramidBand, l: usize, ch: usize, py: usize) -> Option<(usize, usize, &[f32], &[f32])> {+ let (ox, oy) = ((band.0 >> l) as usize, (band.1 >> l) as usize);+ let (lw, lh, colours) = &band.2[l];+ (py >= oy && py - oy < *lh).then(|| {+ let y = py - oy;+ (ox, *lw, &band.3[l][y * lw..(y + 1) * lw], &colours[y * lw * ch..(y + 1) * lw * ch])+ })}/// Multi-band blend of `imgs` into a `w × h` panorama (origin 0,0) with one weight map per image@@ -1119,22 +1194,37 @@ pub fn multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec<f32>], lelet gx1 = (im.x0 + im.w as i32 + margin).min(w as i32);let gy1 = (im.y0 + im.h as i32 + margin).min(h as i32);let (gw, gh) = ((gx1 - gx0).max(1) as usize, (gy1 - gy0).max(1) as usize);+ // Each grid pixel takes the image pixel that lands on it (every image pixel lands on at+ // most one), so rows of the grid are independent and fill in parallel.+ let src_of = |gx: usize, gy: usize| -> Option<usize> {+ let (x, y) = (gx as i64 + gx0 as i64 - im.x0 as i64, gy as i64 + gy0 as i64 - im.y0 as i64);+ (x >= 0 && y >= 0 && (x as usize) < im.w && (y as usize) < im.h).then(|| y as usize * im.w + x as usize)+ };let mut px = vec![0.0f32; gw * gh * ch];+ par_rows(&mut px, gw, ch, |gy, row| {+ for gx in 0..gw {+ if let Some(i) = src_of(gx, gy) {+ row[gx * ch..(gx + 1) * ch].copy_from_slice(&im.px[i * ch..(i + 1) * ch]);+ }+ }+ });let mut cov = vec![0.0f32; gw * gh];+ par_rows(&mut cov, gw, 1, |gy, row| {+ for (gx, o) in row.iter_mut().enumerate() {+ if let Some(i) = src_of(gx, gy) {+ *o = im.alpha[i];+ }+ }+ });let mut wt = vec![0.0f32; gw * gh];- for y in 0..im.h {- for x in 0..im.w {- let (gx, gy) = (im.x0 + x as i32 - gx0, im.y0 + y as i32 - gy0);- if gx < 0 || gy < 0 || gx as usize >= gw || gy as usize >= gh {- continue;+ par_rows(&mut wt, gw, 1, |gy, row| {+ for (gx, o) in row.iter_mut().enumerate() {+ if let Some(i) = src_of(gx, gy) {+ *o = weights[k][i] * im.alpha[i].min(1.0);}- let (i, g) = (y * im.w + x, gy as usize * gw + gx as usize);- cov[g] = im.alpha[i];- wt[g] = weights[k][i] * im.alpha[i].min(1.0);- px[g * ch..(g + 1) * ch].copy_from_slice(&im.px[i * ch..(i + 1) * ch]);}- }- let bin: Vec<f32> = cov.iter().map(|a| if *a > 0.5 { 1.0 } else { 0.0 }).collect();+ });+ let bin: Vec<f32> = par_map1(&cov, |a| if a > 0.5 { 1.0 } else { 0.0 });push_pull(gw, gh, ch, &mut px, &bin);// Laplacian of the colours, Gaussian of the weights.let mut lap: Vec<(usize, usize, Vec<f32>)> = Vec::new();@@ -1148,7 +1238,7 @@ pub fn multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec<f32>], le}let (nw, nh, down) = reduce(cw, chh, ch, &cur);let up = expand(nw, nh, ch, &down, cw, chh);- lap.push((cw, chh, cur.iter().zip(&up).map(|(a, b)| a - b).collect()));+ lap.push((cw, chh, par_zip(&cur, &up, |a, b| a - b)));gau.push(cwt.clone());let (_, _, wdown) = reduce(cw, chh, 1, &cwt);cw = nw;@@ -1158,41 +1248,57 @@ pub fn multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec<f32>], le}(gx0, gy0, lap, gau)});- for (gx0, gy0, lap, gau) in &bands {- for (l, ((lw, lh, band), g)) in lap.iter().zip(gau).enumerate() {- let (ox, oy) = ((gx0 >> l) as usize, (gy0 >> l) as usize);- let (pw, ph) = sizes[l];- for y in 0..*lh {- let py = oy + y;- if py >= ph {- break;+ // Accumulate the bands. Each pixel adds the bands in the same order as the serial loop (per+ // level, bands one after another), but rows of a level are independent, so they run in+ // parallel: every row walks the bands itself.+ for l in 0..levels {+ let pw = sizes[l].0;+ par_rows(&mut wsum[l], pw, 1, |py, row| {+ for b in &bands {+ let Some((ox, lw, g, _)) = band_row(b, l, ch, py) else { continue };+ for x in 0..lw {+ let px = ox + x;+ if px >= pw {+ break;+ }+ let k = g[x];+ if k <= 0.0 {+ continue;+ }+ row[px] += k;}- for x in 0..*lw {+ }+ });+ par_rows(&mut acc[l], pw, ch, |py, row| {+ for b in &bands {+ let Some((ox, lw, g, band)) = band_row(b, l, ch, py) else { continue };+ for x in 0..lw {let px = ox + x;if px >= pw {break;}- let (i, p) = (y * lw + x, py * pw + px);- let k = g[i];+ let k = g[x];if k <= 0.0 {continue;}- wsum[l][p] += k;for c in 0..ch {- acc[l][p * ch + c] += k * band[i * ch + c];+ row[px * ch + c] += k * band[x * ch + c];}}}- }+ });}for l in 0..levels {- let (pw, ph) = sizes[l];- for p in 0..pw * ph {- let k = wsum[l][p];- for c in 0..ch {- acc[l][p * ch + c] = if k > 1e-8 { acc[l][p * ch + c] / k } else { 0.0 };+ let pw = sizes[l].0;+ let ws = &wsum[l];+ par_rows(&mut acc[l], pw, ch, |py, row| {+ for x in 0..pw {+ let k = ws[py * pw + x];+ for c in 0..ch {+ row[x * ch + c] = if k > 1e-8 { row[x * ch + c] / k } else { 0.0 };+ }}- }+ });}// Collapse.// `levels ≥ 1`, so there is always a coarsest level.@@ -1201,22 +1307,27 @@ pub fn multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec<f32>], lelet (pw, ph) = sizes[l];let (sw, sh) = sizes[l + 1];let up = expand(sw, sh, ch, &cur, pw, ph);- cur = acc[l].iter().zip(&up).map(|(a, b)| a + b).collect();+ cur = par_zip(&acc[l], &up, |a, b| a + b);}- // Coverage: union of the images.+ // Coverage: union of the images. Rows are independent; each walks the images in order, so a+ // pixel sees the same sequence of `max` calls as in the serial loop.let mut cov = vec![0.0f32; w * h];- for im in imgs {- for y in 0..im.h {+ par_rows(&mut cov, w, 1, |py, row| {+ for im in imgs {+ let y = py as i64 - im.y0 as i64;+ if y < 0 || y as usize >= im.h {+ continue;+ }for x in 0..im.w {- let (px, py) = (im.x0 + x as i32, im.y0 + y as i32);- if px < 0 || py < 0 || px as usize >= w || py as usize >= h {+ let px = im.x0 + x as i32;+ if px < 0 || px as usize >= w {continue;}- let p = py as usize * w + px as usize;- cov[p] = cov[p].max(im.alpha[y * im.w + x]);+ let p = px as usize;+ row[p] = row[p].max(im.alpha[y as usize * im.w + x]);}}- }+ });(cur, cov)}@@ -1431,3 +1542,389 @@ mod tests {assert!(cov.iter().all(|c| *c == 1.0));}}++/// The row-parallel `reduce` / `expand` / `push_pull` / `multiband` against the serial code they+/// replaced, kept below verbatim as the reference. Every output must stay bit for bit the same.+#[cfg(test)]+mod parallel_tests {+ use super::*;++ fn mix(mut z: u64) -> u64 {+ z = z.wrapping_add(0x9E37_79B9_7F4A_7C15);+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);+ z ^ (z >> 31)+ }++ /// Deterministic data from integer arithmetic only (no libm): mostly `0..1`, with negatives,+ /// signed zeros and large values so a different order of operations cannot hide.+ fn noise(len: usize, seed: u64) -> Vec<f32> {+ (0..len as u64)+ .map(|i| {+ let z = mix(seed.wrapping_mul(0x1234_5678_9ABC).wrapping_add(i));+ let v = (z >> 40) as f32 / 16_777_216.0;+ match z & 31 {+ 0 => -v,+ 1 => -0.0,+ 2 => v * 1000.0,+ 3 => 0.0,+ _ => v,+ }+ })+ .collect()+ }++ /// Weights with exact zeros, exact ones and partial values, in blobs and noise.+ fn weights(w: usize, h: usize, seed: u64) -> Vec<f32> {+ (0..w * h)+ .map(|i| {+ let (x, y) = (i % w, i / w);+ let z = mix(seed + i as u64);+ if (x / 5 + y / 3) % 3 == 0 {+ 0.0+ } else if z.is_multiple_of(7) {+ ((z >> 20) % 100) as f32 / 100.0+ } else {+ 1.0+ }+ })+ .collect()+ }++ fn bits(v: &[f32]) -> Vec<u32> {+ v.iter().map(|x| x.to_bits()).collect()+ }++ fn fnv(parts: &[&[f32]]) -> u64 {+ let mut h = 0xcbf2_9ce4_8422_2325u64;+ for p in parts {+ for x in *p {+ h ^= x.to_bits() as u64;+ h = h.wrapping_mul(0x0000_0100_0000_01b3);+ }+ }+ h+ }++ /// Sizes that cross the odd / even and tiny cases (1 wide, 1 high, 1×1, odd, power of two + 1).+ const SIZES: [(usize, usize); 12] = [(1, 1), (1, 9), (9, 1), (2, 2), (3, 5), (4, 4), (17, 13), (64, 40), (65, 41), (97, 61), (130, 7), (7, 130)];++ fn ref_reduce(w: usize, h: usize, ch: usize, src: &[f32]) -> (usize, usize, Vec<f32>) {+ let (nw, nh) = (w.div_ceil(2), h.div_ceil(2));+ let k = [1.0f32, 4.0, 6.0, 4.0, 1.0];+ // Separable 5-tap binomial, then decimate.+ let mut tmp = vec![0.0f32; nw * h * ch];+ for y in 0..h {+ for x in 0..nw {+ for c in 0..ch {+ let mut s = 0.0;+ for (t, kv) in k.iter().enumerate() {+ let xx = (2 * x as i64 + t as i64 - 2).clamp(0, w as i64 - 1) as usize;+ s += kv * src[(y * w + xx) * ch + c];+ }+ tmp[(y * nw + x) * ch + c] = s / 16.0;+ }+ }+ }+ let mut out = vec![0.0f32; nw * nh * ch];+ for y in 0..nh {+ for x in 0..nw {+ for c in 0..ch {+ let mut s = 0.0;+ for (t, kv) in k.iter().enumerate() {+ let yy = (2 * y as i64 + t as i64 - 2).clamp(0, h as i64 - 1) as usize;+ s += kv * tmp[(yy * nw + x) * ch + c];+ }+ out[(y * nw + x) * ch + c] = s / 16.0;+ }+ }+ }+ (nw, nh, out)+ }++ fn ref_expand(sw: usize, sh: usize, ch: usize, src: &[f32], w: usize, h: usize) -> Vec<f32> {+ // Bilinear upsampling at half-pixel-aligned positions.+ let mut out = vec![0.0f32; w * h * ch];+ for y in 0..h {+ let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sh - 1) as f32);+ let (y0, ty) = (fy.floor() as usize, fy - fy.floor());+ let y1 = (y0 + 1).min(sh - 1);+ for x in 0..w {+ let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sw - 1) as f32);+ let (x0, tx) = (fx.floor() as usize, fx - fx.floor());+ let x1 = (x0 + 1).min(sw - 1);+ for c in 0..ch {+ let p = |xx: usize, yy: usize| src[(yy * sw + xx) * ch + c];+ let top = p(x0, y0) + (p(x1, y0) - p(x0, y0)) * tx;+ let bot = p(x0, y1) + (p(x1, y1) - p(x0, y1)) * tx;+ out[(y * w + x) * ch + c] = top + (bot - top) * ty;+ }+ }+ }+ out+ }++ fn ref_push_pull(w: usize, h: usize, ch: usize, px: &mut [f32], wt: &[f32]) {+ if w <= 1 && h <= 1 {+ return;+ }+ let (nw, nh) = (w.div_ceil(2), h.div_ceil(2));+ let mut cpx = vec![0.0f32; nw * nh * ch];+ let mut cw = vec![0.0f32; nw * nh];+ for y in 0..h {+ for x in 0..w {+ let (i, j) = (y * w + x, (y / 2) * nw + x / 2);+ let a = wt[i];+ cw[j] += a;+ for c in 0..ch {+ cpx[j * ch + c] += a * px[i * ch + c];+ }+ }+ }+ for j in 0..nw * nh {+ if cw[j] > 0.0 {+ for c in 0..ch {+ cpx[j * ch + c] /= cw[j];+ }+ cw[j] = 1.0;+ }+ }+ if cw.contains(&0.0) && cw.iter().any(|v| *v > 0.0) {+ ref_push_pull(nw, nh, ch, &mut cpx, &cw);+ }+ for y in 0..h {+ for x in 0..w {+ let i = y * w + x;+ if wt[i] < 1.0 {+ let j = (y / 2) * nw + x / 2;+ let a = wt[i];+ for c in 0..ch {+ px[i * ch + c] = a * px[i * ch + c] + (1.0 - a) * cpx[j * ch + c];+ }+ }+ }+ }+ }++ fn ref_multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec<f32>], levels: usize) -> (Vec<f32>, Vec<f32>) {+ let ch = imgs.first().map_or(1, |i| i.ch);+ let levels = levels.max(1);+ let align = 1i32 << (levels - 1);+ // Level sizes of the panorama.+ let mut sizes = vec![(w, h)];+ for _ in 1..levels {+ let Some(&(pw, ph)) = sizes.last() else { break };+ sizes.push((pw.div_ceil(2), ph.div_ceil(2)));+ }+ let mut acc: Vec<Vec<f32>> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh * ch]).collect();+ let mut wsum: Vec<Vec<f32>> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh]).collect();+ let margin = align * 4;+ // Each image on its ROI grown by a margin and aligned to the coarsest level's grid.+ let bands = par_map(imgs.len(), |k| {+ let im = &imgs[k];+ let gx0 = ((im.x0 - margin).max(0) / align) * align;+ let gy0 = ((im.y0 - margin).max(0) / align) * align;+ let gx1 = (im.x0 + im.w as i32 + margin).min(w as i32);+ let gy1 = (im.y0 + im.h as i32 + margin).min(h as i32);+ let (gw, gh) = ((gx1 - gx0).max(1) as usize, (gy1 - gy0).max(1) as usize);+ let mut px = vec![0.0f32; gw * gh * ch];+ let mut cov = vec![0.0f32; gw * gh];+ let mut wt = vec![0.0f32; gw * gh];+ for y in 0..im.h {+ for x in 0..im.w {+ let (gx, gy) = (im.x0 + x as i32 - gx0, im.y0 + y as i32 - gy0);+ if gx < 0 || gy < 0 || gx as usize >= gw || gy as usize >= gh {+ continue;+ }+ let (i, g) = (y * im.w + x, gy as usize * gw + gx as usize);+ cov[g] = im.alpha[i];+ wt[g] = weights[k][i] * im.alpha[i].min(1.0);+ px[g * ch..(g + 1) * ch].copy_from_slice(&im.px[i * ch..(i + 1) * ch]);+ }+ }+ let bin: Vec<f32> = cov.iter().map(|a| if *a > 0.5 { 1.0 } else { 0.0 }).collect();+ ref_push_pull(gw, gh, ch, &mut px, &bin);+ // Laplacian of the colours, Gaussian of the weights.+ let mut lap: Vec<(usize, usize, Vec<f32>)> = Vec::new();+ let mut gau: Vec<Vec<f32>> = Vec::new();+ let (mut cw, mut chh, mut cur, mut cwt) = (gw, gh, px, wt);+ for l in 0..levels {+ if l + 1 == levels {+ lap.push((cw, chh, cur.clone()));+ gau.push(cwt.clone());+ break;+ }+ let (nw, nh, down) = ref_reduce(cw, chh, ch, &cur);+ let up = ref_expand(nw, nh, ch, &down, cw, chh);+ lap.push((cw, chh, cur.iter().zip(&up).map(|(a, b)| a - b).collect()));+ gau.push(cwt.clone());+ let (_, _, wdown) = ref_reduce(cw, chh, 1, &cwt);+ cw = nw;+ chh = nh;+ cur = down;+ cwt = wdown;+ }+ (gx0, gy0, lap, gau)+ });+ for (gx0, gy0, lap, gau) in &bands {+ for (l, ((lw, lh, band), g)) in lap.iter().zip(gau).enumerate() {+ let (ox, oy) = ((gx0 >> l) as usize, (gy0 >> l) as usize);+ let (pw, ph) = sizes[l];+ for y in 0..*lh {+ let py = oy + y;+ if py >= ph {+ break;+ }+ for x in 0..*lw {+ let px = ox + x;+ if px >= pw {+ break;+ }+ let (i, p) = (y * lw + x, py * pw + px);+ let k = g[i];+ if k <= 0.0 {+ continue;+ }+ wsum[l][p] += k;+ for c in 0..ch {+ acc[l][p * ch + c] += k * band[i * ch + c];+ }+ }+ }+ }+ }+ for l in 0..levels {+ let (pw, ph) = sizes[l];+ for p in 0..pw * ph {+ let k = wsum[l][p];+ for c in 0..ch {+ acc[l][p * ch + c] = if k > 1e-8 { acc[l][p * ch + c] / k } else { 0.0 };+ }+ }+ }+ // Collapse.+ // `levels ≥ 1`, so there is always a coarsest level.+ let Some(mut cur) = acc.pop() else { return (vec![0.0; w * h * ch], vec![0.0; w * h]) };+ for l in (0..levels - 1).rev() {+ let (pw, ph) = sizes[l];+ let (sw, sh) = sizes[l + 1];+ let up = ref_expand(sw, sh, ch, &cur, pw, ph);+ cur = acc[l].iter().zip(&up).map(|(a, b)| a + b).collect();+ }+ // Coverage: union of the images.+ let mut cov = vec![0.0f32; w * h];+ for im in imgs {+ for y in 0..im.h {+ for x in 0..im.w {+ let (px, py) = (im.x0 + x as i32, im.y0 + y as i32);+ if px < 0 || py < 0 || px as usize >= w || py as usize >= h {+ continue;+ }+ let p = py as usize * w + px as usize;+ cov[p] = cov[p].max(im.alpha[y * im.w + x]);+ }+ }+ }+ (cur, cov)+ }++ #[test]+ fn reduce_and_expand_match_the_serial_code() {+ for (n, &(w, h)) in SIZES.iter().enumerate() {+ for ch in [1usize, 3, 4] {+ let src = noise(w * h * ch, n as u64 * 7 + ch as u64);+ let (nw, nh, got) = reduce(w, h, ch, &src);+ let (rw, rh, want) = ref_reduce(w, h, ch, &src);+ assert_eq!((nw, nh), (rw, rh));+ assert_eq!(bits(&got), bits(&want), "reduce {w}x{h}x{ch}");+ // Expand back to the original size and to sizes that are not twice the source's.+ for (ew, eh) in [(w, h), (2 * nw, 2 * nh), (2 * nw - 1, 2 * nh + 1), (w + 3, h + 5)] {+ let got = expand(nw, nh, ch, &want, ew, eh);+ let want_up = ref_expand(nw, nh, ch, &want, ew, eh);+ assert_eq!(bits(&got), bits(&want_up), "expand {nw}x{nh}x{ch} to {ew}x{eh}");+ }+ }+ }+ }++ #[test]+ fn push_pull_matches_the_serial_code() {+ for (n, &(w, h)) in SIZES.iter().enumerate() {+ for ch in [1usize, 3] {+ for variant in 0..3u64 {+ let wt = match variant {+ 0 => weights(w, h, n as u64),+ 1 => vec![1.0; w * h],+ // A single covered pixel: every level of the recursion has to fill from it.+ _ => (0..w * h).map(|i| if i == (w * h) / 3 { 1.0 } else { 0.0 }).collect(),+ };+ let px = noise(w * h * ch, 100 + n as u64);+ let (mut got, mut want) = (px.clone(), px);+ push_pull(w, h, ch, &mut got, &wt);+ ref_push_pull(w, h, ch, &mut want, &wt);+ assert_eq!(bits(&got), bits(&want), "push_pull {w}x{h}x{ch} variant {variant}");+ }+ }+ }+ }++ /// ROIs of assorted sizes and offsets (some sticking out of the canvas), with holes in the alpha.+ fn rois(w: usize, h: usize, ch: usize, seed: u64) -> (Vec<RoiImage>, Vec<Vec<f32>>) {+ let specs =+ [(0i32, 0i32, w * 2 / 3, h), (w as i32 / 3, -(h as i32) / 5, w * 2 / 3 + 1, h * 3 / 4 + 1), (-(w as i32) / 4, h as i32 / 2, w / 2 + 1, h / 2 + 3)];+ let imgs: Vec<RoiImage> = specs+ .iter()+ .enumerate()+ .map(|(k, &(x0, y0, iw, ih))| {+ let (iw, ih) = (iw.max(1), ih.max(1));+ let mut alpha = vec![1.0f32; iw * ih];+ for (i, a) in alpha.iter_mut().enumerate() {+ let z = mix(seed + k as u64 * 1000 + i as u64);+ if (i % iw) / 4 % 5 == 2 && (i / iw) % 6 < 3 {+ *a = 0.0;+ } else if z.is_multiple_of(11) {+ *a = 0.3;+ }+ }+ RoiImage { x0, y0, w: iw, h: ih, ch, px: noise(iw * ih * ch, seed + k as u64), alpha }+ })+ .collect();+ let wts = imgs.iter().enumerate().map(|(k, r)| weights(r.w, r.h, seed + 50 + k as u64)).collect();+ (imgs, wts)+ }++ #[test]+ fn multiband_matches_the_serial_code() {+ for (n, &(w, h)) in [(1usize, 1usize), (5, 3), (40, 30), (97, 61), (130, 70), (64, 64), (201, 129)].iter().enumerate() {+ for ch in [1usize, 3] {+ let (imgs, wts) = rois(w, h, ch, n as u64 * 31 + ch as u64);+ for levels in [1usize, 2, 3, 5, 7] {+ let got = multiband(w, h, &imgs, &wts, levels);+ let want = ref_multiband(w, h, &imgs, &wts, levels);+ assert_eq!(bits(&got.0), bits(&want.0), "colours {w}x{h}x{ch} levels {levels}");+ assert_eq!(bits(&got.1), bits(&want.1), "coverage {w}x{h}x{ch} levels {levels}");+ }+ }+ }+ // No images at all, and zero levels.+ assert_eq!(multiband(9, 7, &[], &[], 3).0.len(), ref_multiband(9, 7, &[], &[], 3).0.len());+ }++ /// Hashes recorded from the code before it was made parallel (plain f32 arithmetic only, so+ /// they hold on every platform).+ #[test]+ fn multiband_hashes_recorded_from_the_serial_code() {+ let (imgs, wts) = rois(97, 61, 3, 5);+ let (px, cov) = multiband(97, 61, &imgs, &wts, 5);+ assert_eq!(fnv(&[&px, &cov]), 0xf89a5726082ebb6c, "97x61 rgb, 5 levels");+ let (imgs, wts) = rois(130, 70, 1, 9);+ let (px, cov) = multiband(130, 70, &imgs, &wts, 7);+ assert_eq!(fnv(&[&px, &cov]), 0xb7d7ddc59d201730, "130x70 grey, 7 levels");+ let wt = weights(65, 41, 3);+ let mut px = noise(65 * 41 * 3, 4);+ push_pull(65, 41, 3, &mut px, &wt);+ assert_eq!(fnv(&[&px]), 0x50ea36a84ca9a68f, "push_pull 65x41 rgb");+ let (nw, nh, r) = reduce(65, 41, 3, &px);+ assert_eq!(fnv(&[&r, &expand(nw, nh, 3, &r, 65, 41)]), 0x51823acfb4206dd8, "reduce + expand 65x41 rgb");+ }+}