#[cfg(feature = "profiling")]
pub(crate) use prof::{RasterClass, RasterProf};
#[cfg(feature = "profiling")]
mod prof {
use crate::profiling::ProfileReport;
use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) enum RasterClass {
#[default]
Path,
Clip,
Glyph,
Other,
}
macro_rules! raster_class_prof {
($($field:ident),* $(,)?) => {
#[derive(Debug, Default, Clone, Copy)]
pub(crate) struct RasterClassProf {
$(pub(crate) $field: u64,)*
}
impl RasterClassProf {
fn merge(&mut self, other: &Self) {
$(self.$field += other.$field;)*
}
fn drain_into(&self, class: RasterClass, out: &mut ProfileReport) {
$(
if self.$field != 0 {
let name: &'static str = match class {
RasterClass::Path => concat!("raster.path.", stringify!($field)),
RasterClass::Clip => concat!("raster.clip.", stringify!($field)),
RasterClass::Glyph => concat!("raster.glyph.", stringify!($field)),
RasterClass::Other => concat!("raster.other.", stringify!($field)),
};
if stringify!($field).starts_with("ns_") {
out.add_duration(name, Duration::from_nanos(self.$field));
} else {
out.increment(name, self.$field);
}
}
)*
}
}
};
}
raster_class_prof!(
fills,
fills_no_edges,
fills_no_rows,
subpaths,
edges,
edge_rows,
route_accum,
route_aet_sparse,
route_aet_oversize,
accum_window_cells,
aet_window_cells,
rows_window,
rows_emitted,
covered_span_px,
accum_cells_swept,
aet_rows_dense_many,
aet_rows_dense_short,
aet_rows_sparse,
aet_rows_repeated,
aet_dense_cells_swept,
aet_active_visits,
fills_rows_le4,
fills_rows_le32,
fills_rows_gt32,
ns_rows_le4,
ns_rows_le32,
ns_rows_gt32,
ns_total,
ns_edge_build,
ns_accum_deposit,
ns_accum_sweep,
ns_aet_setup,
ns_aet_sweep,
ns_callback,
clock_reads,
);
#[derive(Debug, Default, Clone)]
pub(crate) struct RasterProf {
pub(crate) class: RasterClass,
pub(crate) time_fills: bool,
pub(crate) time_rows: bool,
pub(crate) fill_rows: u64,
by_class: [RasterClassProf; 4],
}
impl RasterProf {
#[inline]
pub(crate) fn cur(&mut self) -> &mut RasterClassProf {
&mut self.by_class[self.class as usize]
}
pub(crate) fn merge(&mut self, other: &Self) {
for (mine, theirs) in self.by_class.iter_mut().zip(&other.by_class) {
mine.merge(theirs);
}
}
pub(crate) fn drain_into(&mut self, out: &mut ProfileReport) {
const CLASSES: [RasterClass; 4] = [
RasterClass::Path,
RasterClass::Clip,
RasterClass::Glyph,
RasterClass::Other,
];
for (class, counters) in CLASSES.iter().zip(&mut self.by_class) {
counters.drain_into(*class, out);
*counters = RasterClassProf::default();
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FillRule {
NonZero,
EvenOdd,
}
#[derive(Debug, Clone, Copy)]
struct Edge {
y_top: f32,
y_bot: f32,
x_at_top: f32,
dxdy: f32,
dir: f32,
}
const MAX_WINDOW_CELLS: usize = 1 << 20;
const CACHE_WINDOW_CELLS: usize = 1 << 13;
const AVX2_MIN_SPAN: usize = usize::MAX;
const COMPACT_RUN_MIN: usize = 16;
const COMPACT_GAP_MIN_SPAN: usize = 32;
const COMPACT_GAP_PROBE: usize = 4;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct CovRun {
pub x0: u32,
pub x1: u32,
pub fill: Option<u8>,
}
#[derive(Debug, Default)]
pub struct RasterKernel {
edges: Vec<Edge>,
acc: Vec<f32>,
row_min: Vec<u32>,
row_max: Vec<u32>,
cov: Vec<u8>,
acc_row: Vec<f32>,
aet_order: Vec<u32>,
aet_bucket_start: Vec<u32>,
aet_erend: Vec<u32>,
aet_active: Vec<u32>,
aet_active_next: Vec<u32>,
aet_touched: Vec<(u32, u32)>,
row_runs: Vec<CovRun>,
dirty: bool,
pub last_edges: u64,
pub last_rows: u64,
pub last_covered: u64,
#[cfg(feature = "profiling")]
pub(crate) prof: RasterProf,
}
impl RasterKernel {
pub fn fill(
&mut self,
points: &[[f32; 2]],
subpaths: &[(usize, usize)],
width: usize,
height: usize,
rule: FillRule,
row: impl FnMut(usize, usize, usize, &mut [u8]),
) {
let _ = self.fill_cancellable(points, subpaths, width, height, rule, None, row);
}
#[allow(clippy::too_many_arguments)]
pub fn fill_cancellable(
&mut self,
points: &[[f32; 2]],
subpaths: &[(usize, usize)],
width: usize,
height: usize,
rule: FillRule,
should_cancel: Option<&(dyn Fn() -> bool + Send + Sync)>,
row: impl FnMut(usize, usize, usize, &mut [u8]),
) -> bool {
self.fill_cancellable_in(
points,
subpaths,
width,
height,
rule,
0..usize::MAX,
should_cancel,
row,
)
}
#[allow(clippy::too_many_arguments)]
pub fn fill_cancellable_in(
&mut self,
points: &[[f32; 2]],
subpaths: &[(usize, usize)],
width: usize,
height: usize,
rule: FillRule,
rows: std::ops::Range<usize>,
should_cancel: Option<&(dyn Fn() -> bool + Send + Sync)>,
mut row: impl FnMut(usize, usize, usize, &mut [u8]),
) -> bool {
self.fill_impl(
points,
subpaths,
width,
height,
rule,
rows,
should_cancel,
false,
|y, x0, x1, cov, _| {
row(y, x0, x1, cov);
true
},
)
}
#[cfg_attr(not(test), allow(dead_code))]
#[allow(clippy::too_many_arguments)]
pub(crate) fn fill_runs_cancellable(
&mut self,
points: &[[f32; 2]],
subpaths: &[(usize, usize)],
width: usize,
height: usize,
rule: FillRule,
should_cancel: Option<&(dyn Fn() -> bool + Send + Sync)>,
row: impl FnMut(usize, usize, usize, &mut [u8], &[CovRun]) -> bool,
) -> bool {
self.fill_runs_cancellable_in(
points,
subpaths,
width,
height,
rule,
0..usize::MAX,
should_cancel,
row,
)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn fill_runs_cancellable_in(
&mut self,
points: &[[f32; 2]],
subpaths: &[(usize, usize)],
width: usize,
height: usize,
rule: FillRule,
rows: std::ops::Range<usize>,
should_cancel: Option<&(dyn Fn() -> bool + Send + Sync)>,
row: impl FnMut(usize, usize, usize, &mut [u8], &[CovRun]) -> bool,
) -> bool {
self.fill_impl(
points,
subpaths,
width,
height,
rule,
rows,
should_cancel,
true,
row,
)
}
#[allow(clippy::too_many_arguments)]
fn fill_impl(
&mut self,
points: &[[f32; 2]],
subpaths: &[(usize, usize)],
width: usize,
height: usize,
rule: FillRule,
rows: std::ops::Range<usize>,
should_cancel: Option<&(dyn Fn() -> bool + Send + Sync)>,
runs_mode: bool,
row: impl FnMut(usize, usize, usize, &mut [u8], &[CovRun]) -> bool,
) -> bool {
if self.dirty {
self.reset_cancelled_fill();
}
self.dirty = true;
#[cfg(feature = "profiling")]
let prof_start = self.prof.time_fills.then(std::time::Instant::now);
#[cfg(feature = "profiling")]
let time_rows = self.prof.time_rows;
#[cfg(feature = "profiling")]
let (mut callback_ns, mut callback_rows) = (0u64, 0u64);
#[cfg(feature = "profiling")]
let mut row = row;
#[cfg(feature = "profiling")]
let row = |y: usize, x0: usize, x1: usize, cov: &mut [u8], runs: &[CovRun]| -> bool {
callback_rows += 1;
if time_rows {
let start = std::time::Instant::now();
let dirty = row(y, x0, x1, cov, runs);
callback_ns += start.elapsed().as_nanos() as u64;
dirty
} else {
row(y, x0, x1, cov, runs)
}
};
#[cfg(feature = "profiling")]
{
self.prof.fill_rows = 0;
}
let finished = self.fill_inner(
points,
subpaths,
width,
height,
rule,
rows,
should_cancel,
runs_mode,
row,
);
#[cfg(feature = "profiling")]
{
let total = prof_start.map_or(0, |start| start.elapsed().as_nanos() as u64);
let rows = self.prof.fill_rows;
let covered = if rows > 0 { self.last_covered } else { 0 };
let c = self.prof.cur();
c.ns_total += total;
c.ns_callback += callback_ns;
c.rows_emitted += callback_rows;
c.covered_span_px += covered;
c.clock_reads += if prof_start.is_some() { 2 } else { 0 }
+ if time_rows { 2 * callback_rows } else { 0 };
if rows > 32 {
c.fills_rows_gt32 += 1;
c.ns_rows_gt32 += total;
} else if rows > 4 {
c.fills_rows_le32 += 1;
c.ns_rows_le32 += total;
} else if rows > 0 {
c.fills_rows_le4 += 1;
c.ns_rows_le4 += total;
}
}
self.dirty = false;
finished
}
#[allow(clippy::too_many_arguments)]
fn fill_inner(
&mut self,
points: &[[f32; 2]],
subpaths: &[(usize, usize)],
width: usize,
height: usize,
rule: FillRule,
rows: std::ops::Range<usize>,
should_cancel: Option<&(dyn Fn() -> bool + Send + Sync)>,
runs_mode: bool,
row: impl FnMut(usize, usize, usize, &mut [u8], &[CovRun]) -> bool,
) -> bool {
if width == 0 || height == 0 {
return true;
}
if should_cancel.is_some_and(|cancel| cancel()) {
return false;
}
if self.cov.len() < width {
self.cov.resize(width, 0);
}
#[cfg(feature = "profiling")]
let mut lap = self.prof.time_fills.then(crate::profiling::Lap::start);
#[cfg(feature = "profiling")]
let prof_timed = u64::from(self.prof.time_fills);
self.edges.clear();
let mut y_min = f32::INFINITY;
let mut y_max = f32::NEG_INFINITY;
let mut x_min = f32::INFINITY;
let mut x_max = f32::NEG_INFINITY;
for (subpath_index, &(start, end)) in subpaths.iter().enumerate() {
if subpath_index & 0x3f == 0 && should_cancel.is_some_and(|cancel| cancel()) {
self.reset_cancelled_fill();
return false;
}
let n = end - start;
if n < 2 {
continue;
}
for i in 0..n {
let a = points[start + i];
let b = points[start + (i + 1) % n];
if a[1] == b[1] {
continue;
}
let (y_top, y_bot, x_at_top, dir) = if a[1] < b[1] {
(a[1], b[1], a[0], 1.0)
} else {
(b[1], a[1], b[0], -1.0)
};
let dxdy = (b[0] - a[0]) / (b[1] - a[1]);
self.edges.push(Edge {
y_top,
y_bot,
x_at_top,
dxdy,
dir,
});
y_min = y_min.min(y_top);
y_max = y_max.max(y_bot);
let x_at_bot = x_at_top + dxdy * (y_bot - y_top);
x_min = x_min.min(x_at_top.min(x_at_bot));
x_max = x_max.max(x_at_top.max(x_at_bot));
}
}
#[cfg(feature = "profiling")]
{
let edge_build = crate::profiling::lap_opt(&mut lap);
let edges = self.edges.len() as u64;
let c = self.prof.cur();
c.ns_edge_build += edge_build;
c.clock_reads += 2 * prof_timed;
c.fills += 1;
c.subpaths += subpaths.len() as u64;
c.edges += edges;
if edges == 0 {
c.fills_no_edges += 1;
}
}
if self.edges.is_empty() {
return true;
}
self.last_edges = self.edges.len() as u64;
let row_start = y_min.floor().max(0.0) as usize;
let row_end = (y_max.ceil().min(height as f32)) as usize;
self.last_rows = row_end.saturating_sub(row_start) as u64;
self.last_covered = 0;
if row_end <= row_start {
#[cfg(feature = "profiling")]
{
self.prof.cur().fills_no_rows += 1;
}
return true;
}
let emit_start = row_start.max(rows.start);
let emit_end = row_end.min(rows.end);
if emit_end <= emit_start {
self.last_rows = 0;
return true;
}
self.last_rows = (emit_end - emit_start) as u64;
let fwidth = width as f32;
let bx = (x_min.floor().clamp(0.0, (width - 1) as f32)) as usize;
let right = (x_max.ceil().clamp(0.0, fwidth)) as usize;
let bw = right.saturating_sub(bx).max(1);
let bh = row_end - row_start;
let stride = bw + 2; let cells = stride.saturating_mul(bh);
let sparse = cells > CACHE_WINDOW_CELLS && self.edges.len().saturating_mul(8) < cells;
#[cfg(feature = "profiling")]
{
self.prof.fill_rows = bh as u64;
let c = self.prof.cur();
c.rows_window += bh as u64;
if cells > MAX_WINDOW_CELLS {
c.route_aet_oversize += 1;
c.aet_window_cells += cells as u64;
} else if sparse {
c.route_aet_sparse += 1;
c.aet_window_cells += cells as u64;
} else {
c.route_accum += 1;
c.accum_window_cells += cells as u64;
}
}
if cells > MAX_WINDOW_CELLS || sparse {
let completed = self.fill_scanline_aet(
width,
height,
rule,
row_start,
row_end,
emit_start,
emit_end,
should_cancel,
runs_mode,
row,
);
if !completed {
self.reset_cancelled_fill();
}
return completed;
}
if self.acc.len() < cells {
self.acc.resize(cells, 0.0);
}
if self.row_min.len() < bh {
self.row_min.resize(bh, 0);
self.row_max.resize(bh, 0);
}
for lr in 0..bh {
self.row_min[lr] = u32::MAX;
self.row_max[lr] = 0;
}
for edge_index in 0..self.edges.len() {
if edge_index & 0x3f == 0 && should_cancel.is_some_and(|cancel| cancel()) {
self.reset_cancelled_fill();
return false;
}
let e = self.edges[edge_index];
let er_start =
((e.y_top.floor() as isize).max(row_start as isize) as usize).max(emit_start);
let er_end =
((e.y_bot.ceil() as isize).min(row_end as isize).max(0) as usize).min(emit_end);
#[cfg(feature = "profiling")]
{
self.prof.cur().edge_rows += er_end.saturating_sub(er_start) as u64;
}
if e.dxdy == 0.0 {
let xc = e.x_at_top.clamp(0.0, fwidth);
let c = (xc.floor().clamp(0.0, fwidth - 1.0)) as usize;
let lc = c.saturating_sub(bx).min(stride - 2);
let frac = (c as f32 + 1.0) - xc; for y in er_start..er_end {
if y & 0xff == 0 && should_cancel.is_some_and(|cancel| cancel()) {
self.reset_cancelled_fill();
return false;
}
let yf = y as f32;
let ya = e.y_top.max(yf);
let yb = e.y_bot.min(yf + 1.0);
if yb <= ya {
continue;
}
let cover = (yb - ya) * e.dir;
let this_px = cover * frac;
let lr = y - row_start;
let base = lr * stride;
self.acc[base + lc] += this_px;
self.acc[base + lc + 1] += cover - this_px;
if (lc as u32) < self.row_min[lr] {
self.row_min[lr] = lc as u32;
}
if (lc as u32) > self.row_max[lr] {
self.row_max[lr] = lc as u32;
}
}
} else {
for y in er_start..er_end {
if y & 0xff == 0 && should_cancel.is_some_and(|cancel| cancel()) {
self.reset_cancelled_fill();
return false;
}
let yf = y as f32;
let ya = e.y_top.max(yf);
let yb = e.y_bot.min(yf + 1.0);
if yb <= ya {
continue;
}
let xa = e.x_at_top + (ya - e.y_top) * e.dxdy;
let xb = e.x_at_top + (yb - e.y_top) * e.dxdy;
let lr = y - row_start;
let base = lr * stride;
deposit_edge_row(
&mut self.acc,
base,
xa,
ya,
xb,
yb,
e.dir,
fwidth,
bx,
stride,
&mut self.row_min[lr],
&mut self.row_max[lr],
);
}
}
}
#[cfg(feature = "profiling")]
{
let deposit = crate::profiling::lap_opt(&mut lap);
let c = self.prof.cur();
c.ns_accum_deposit += deposit;
c.clock_reads += 1 * prof_timed;
}
let use_avx2 = coverage_use_avx2();
let mut row = row;
for lr in (emit_start - row_start)..(emit_end - row_start) {
if lr & 0x1f == 0 && should_cancel.is_some_and(|cancel| cancel()) {
self.reset_cancelled_fill();
return false;
}
let cmin = self.row_min[lr];
let cmax = self.row_max[lr];
if cmin > cmax {
continue;
}
let (cmin, cmax) = (cmin as usize, cmax as usize);
#[cfg(feature = "profiling")]
{
self.prof.cur().accum_cells_swept += (cmax - cmin + 1) as u64;
}
let base = lr * stride;
let mut first = width;
let mut last = 0usize;
let find_gaps = cmax - cmin + 1 >= COMPACT_GAP_MIN_SPAN;
let mut emit_runs = false;
#[allow(clippy::absurd_extreme_comparisons)]
if use_avx2 && cmax - cmin + 1 >= AVX2_MIN_SPAN {
let acc = &mut self.acc[base..base + stride];
let mut running = 0.0f32;
for c in cmin..=cmax {
running += acc[c];
acc[c] = running;
}
convert_coverage(&acc[cmin..=cmax], &mut self.cov, bx + cmin, rule);
for c in cmin..=cmax {
let x = bx + c;
if self.cov[x] != 0 {
first = first.min(x);
last = x;
}
acc[c] = 0.0;
}
acc[cmax + 1] = 0.0;
} else if !find_gaps {
let acc = &mut self.acc[base..base + stride];
let mut running = 0.0f32;
for c in cmin..=cmax {
running += acc[c];
acc[c] = 0.0;
let byte = coverage_byte(running, rule);
let x = bx + c;
self.cov[x] = byte;
if byte != 0 {
first = first.min(x);
last = x;
}
}
acc[cmax + 1] = 0.0;
} else {
let acc = &mut self.acc[base..base + stride];
let mut running = 0.0f32;
self.row_runs.clear();
let mut cells_from = cmin;
let mut c = cmin;
emit_runs = runs_mode;
while c <= cmax {
let v = acc[c];
if v == 0.0
&& c + COMPACT_GAP_PROBE <= cmax + 1
&& acc[c + 1..c + COMPACT_GAP_PROBE]
.iter()
.all(|&cell| cell == 0.0)
{
let gap = acc[c..=cmax]
.iter()
.position(|&cell| cell != 0.0)
.unwrap_or(cmax + 1 - c);
let end = c + gap;
let byte = coverage_byte(running, rule);
if runs_mode && gap >= COMPACT_RUN_MIN && (byte == 0 || byte == 255) {
if cells_from < c {
self.row_runs.push(CovRun {
x0: (bx + cells_from) as u32,
x1: (bx + c) as u32,
fill: None,
});
}
if byte != 0 {
self.row_runs.push(CovRun {
x0: (bx + c) as u32,
x1: (bx + end) as u32,
fill: Some(byte),
});
first = first.min(bx + c);
last = bx + end - 1;
}
cells_from = end;
} else if byte != 0 {
self.cov[bx + c..bx + end].fill(byte);
first = first.min(bx + c);
last = bx + end - 1;
}
c = end;
continue;
}
running += v;
acc[c] = 0.0;
let byte = coverage_byte(running, rule);
let x = bx + c;
self.cov[x] = byte;
if byte != 0 {
first = first.min(x);
last = x;
}
c += 1;
}
acc[cmax + 1] = 0.0;
if cells_from <= cmax {
self.row_runs.push(CovRun {
x0: (bx + cells_from) as u32,
x1: (bx + cmax + 1) as u32,
fill: None,
});
}
}
if first <= last {
self.last_covered += (last - first + 1) as u64;
let y = row_start + lr;
if emit_runs {
if row(y, first, last, &mut self.cov, &self.row_runs) {
self.cov[first..=last].fill(0);
} else {
for run in &self.row_runs {
if run.fill.is_none() {
self.cov[run.x0 as usize..run.x1 as usize].fill(0);
}
}
}
} else {
let whole = [CovRun {
x0: first as u32,
x1: last as u32 + 1,
fill: None,
}];
row(y, first, last, &mut self.cov, &whole);
self.cov[first..=last].fill(0);
}
}
}
#[cfg(feature = "profiling")]
{
let sweep = crate::profiling::lap_opt(&mut lap);
let c = self.prof.cur();
c.ns_accum_sweep += sweep;
c.clock_reads += 1 * prof_timed;
}
true
}
fn reset_cancelled_fill(&mut self) {
self.acc.fill(0.0);
self.acc_row.fill(0.0);
self.cov.fill(0);
self.aet_active.clear();
self.aet_active_next.clear();
self.aet_touched.clear();
self.row_runs.clear();
}
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
fn fill_scanline_ref(
&mut self,
width: usize,
_height: usize,
rule: FillRule,
row_start: usize,
row_end: usize,
mut row: impl FnMut(usize, usize, usize, &mut [u8]),
) {
if self.acc_row.len() < width + 1 {
self.acc_row.resize(width + 1, 0.0);
}
let fwidth = width as f32;
for y in row_start..row_end {
let yf = y as f32;
let mut col_min = width;
let mut col_max = 0usize;
for e in &self.edges {
let ya = e.y_top.max(yf);
let yb = e.y_bot.min(yf + 1.0);
if yb <= ya {
continue;
}
let xa = e.x_at_top + (ya - e.y_top) * e.dxdy;
let xb = e.x_at_top + (yb - e.y_top) * e.dxdy;
accumulate(
&mut self.acc_row,
xa,
ya,
xb,
yb,
e.dir,
fwidth,
&mut col_min,
&mut col_max,
);
}
if col_min > col_max {
continue;
}
let mut running = 0.0f32;
let mut first = width;
let mut last = 0usize;
for x in col_min..=col_max {
running += self.acc_row[x];
self.acc_row[x] = 0.0;
let byte = coverage_byte(running, rule);
self.cov[x] = byte;
if byte != 0 {
first = first.min(x);
last = x;
}
}
self.acc_row[col_max + 1] = 0.0;
if first <= last {
self.last_covered += (last - first + 1) as u64;
row(y, first, last, &mut self.cov);
for c in &mut self.cov[first..=last] {
*c = 0;
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn fill_scanline_aet(
&mut self,
width: usize,
_height: usize,
rule: FillRule,
row_start: usize,
row_end: usize,
emit_start: usize,
emit_end: usize,
should_cancel: Option<&(dyn Fn() -> bool + Send + Sync)>,
runs_mode: bool,
mut row: impl FnMut(usize, usize, usize, &mut [u8], &[CovRun]) -> bool,
) -> bool {
if self.acc_row.len() < width + 1 {
self.acc_row.resize(width + 1, 0.0);
}
let fwidth = width as f32;
let bh = row_end - row_start;
#[cfg(feature = "profiling")]
let mut lap = self.prof.time_fills.then(crate::profiling::Lap::start);
#[cfg(feature = "profiling")]
let prof_timed = u64::from(self.prof.time_fills);
self.aet_bucket_start.clear();
self.aet_bucket_start.resize(bh + 1, 0);
if self.aet_erend.len() < self.edges.len() {
self.aet_erend.resize(self.edges.len(), 0);
}
let mut contributing = 0usize;
#[cfg(feature = "profiling")]
let mut prof_edge_rows = 0u64;
for (edge_index, e) in self.edges.iter().enumerate() {
if edge_index & 0xff == 0 && should_cancel.is_some_and(|cancel| cancel()) {
return false;
}
let er_start = (e.y_top.floor() as isize)
.max(row_start as isize)
.max(emit_start as isize);
let er_end = (e.y_bot.ceil() as isize)
.min(row_end as isize)
.max(0)
.min(emit_end as isize);
if er_start >= er_end {
continue; }
let lr = er_start as usize - row_start;
self.aet_bucket_start[lr + 1] += 1; contributing += 1;
#[cfg(feature = "profiling")]
{
prof_edge_rows += (er_end - er_start) as u64;
}
}
for lr in 0..bh {
self.aet_bucket_start[lr + 1] += self.aet_bucket_start[lr];
}
self.aet_order.clear();
self.aet_order.resize(contributing, 0);
self.aet_active_next.clear();
self.aet_active_next
.extend_from_slice(&self.aet_bucket_start[..bh]);
for (i, e) in self.edges.iter().enumerate() {
if i & 0xff == 0 && should_cancel.is_some_and(|cancel| cancel()) {
return false;
}
let er_start = (e.y_top.floor() as isize)
.max(row_start as isize)
.max(emit_start as isize);
let er_end = (e.y_bot.ceil() as isize)
.min(row_end as isize)
.max(0)
.min(emit_end as isize);
if er_start >= er_end {
continue;
}
let lr = er_start as usize - row_start;
let pos = self.aet_active_next[lr] as usize;
self.aet_order[pos] = i as u32;
self.aet_active_next[lr] += 1;
self.aet_erend[i] = er_end as u32;
}
let mut held: Option<(usize, usize)> = None;
self.aet_active.clear();
#[cfg(feature = "profiling")]
{
let setup = crate::profiling::lap_opt(&mut lap);
let c = self.prof.cur();
c.ns_aet_setup += setup;
c.edge_rows += prof_edge_rows;
c.clock_reads += 2 * prof_timed;
}
for lr in (emit_start - row_start)..(emit_end - row_start) {
if lr & 0x0f == 0 && should_cancel.is_some_and(|cancel| cancel()) {
return false;
}
let y = row_start + lr;
let yf = y as f32;
let yu = y as u32;
let prev_active = self.aet_active.len();
let b0 = self.aet_bucket_start[lr] as usize;
let b1 = self.aet_bucket_start[lr + 1] as usize;
self.aet_active_next.clear();
let mut i = 0usize;
let mut j = b0;
while i < self.aet_active.len() && j < b1 {
let a = self.aet_active[i];
if self.aet_erend[a as usize] <= yu {
i += 1;
continue;
}
let bk = self.aet_order[j];
if a < bk {
self.aet_active_next.push(a);
i += 1;
} else {
self.aet_active_next.push(bk);
j += 1;
}
}
while i < self.aet_active.len() {
let a = self.aet_active[i];
if self.aet_erend[a as usize] > yu {
self.aet_active_next.push(a);
}
i += 1;
}
while j < b1 {
self.aet_active_next.push(self.aet_order[j]);
j += 1;
}
std::mem::swap(&mut self.aet_active, &mut self.aet_active_next);
if let Some((first, last)) = held {
let repeat = b0 == b1
&& self.aet_active.len() == prev_active
&& self
.aet_active
.iter()
.all(|&ei| self.edges[ei as usize].y_bot >= yf + 1.0);
if repeat {
#[cfg(feature = "profiling")]
{
self.prof.cur().aet_rows_repeated += 1;
}
self.last_covered += (last - first + 1) as u64;
if row(y, first, last, &mut self.cov, &self.row_runs) {
for c in &mut self.cov[first..=last] {
*c = 0;
}
held = None;
}
continue;
}
for r in &self.row_runs {
if r.fill.is_none() {
self.cov[r.x0 as usize..r.x1 as usize].fill(0);
}
}
held = None;
}
let active = std::mem::take(&mut self.aet_active);
let mut col_min = width;
let mut col_max = 0usize;
let mut all_vertical_full = runs_mode && y < (1 << 24);
self.aet_touched.clear();
for (active_index, &ei) in active.iter().enumerate() {
if active_index & 0xfff == 0 && should_cancel.is_some_and(|cancel| cancel()) {
self.aet_active = active;
return false;
}
let e = self.edges[ei as usize];
let ya = e.y_top.max(yf);
let yb = e.y_bot.min(yf + 1.0);
all_vertical_full &= e.dxdy == 0.0 && ya == yf && yb == yf + 1.0;
if yb <= ya {
continue;
}
let xa = e.x_at_top + (ya - e.y_top) * e.dxdy;
let xb = e.x_at_top + (yb - e.y_top) * e.dxdy;
let mut edge_min = width;
let mut edge_max = 0usize;
accumulate(
&mut self.acc_row,
xa,
ya,
xb,
yb,
e.dir,
fwidth,
&mut edge_min,
&mut edge_max,
);
if edge_min <= edge_max {
col_min = col_min.min(edge_min);
col_max = col_max.max(edge_max);
self.aet_touched
.push((edge_min as u32, edge_max as u32 + 2));
}
}
self.aet_active = active;
#[cfg(feature = "profiling")]
{
self.prof.cur().aet_active_visits += self.aet_active.len() as u64;
}
if col_min > col_max {
continue;
}
#[cfg(feature = "profiling")]
{
let span = (col_max - col_min + 1) as u64;
let intervals = self.aet_touched.len();
let c = self.prof.cur();
if intervals > SPARSE_MAX_INTERVALS {
c.aet_rows_dense_many += 1;
c.aet_dense_cells_swept += span;
} else if (span as usize) < SPARSE_MIN_SPAN {
c.aet_rows_dense_short += 1;
c.aet_dense_cells_swept += span;
} else {
c.aet_rows_sparse += 1;
}
}
self.row_runs.clear();
let (first, last) = convert_row_sparse(
&mut self.acc_row,
&mut self.cov,
&mut self.aet_touched,
col_min,
col_max,
rule,
runs_mode.then_some(&mut self.row_runs),
);
if first <= last {
self.last_covered += (last - first + 1) as u64;
let dirty = row(y, first, last, &mut self.cov, &self.row_runs);
if !runs_mode || dirty {
for c in &mut self.cov[first..=last] {
*c = 0;
}
} else if all_vertical_full {
held = Some((first, last));
} else {
for r in &self.row_runs {
if r.fill.is_none() {
self.cov[r.x0 as usize..r.x1 as usize].fill(0);
}
}
}
}
}
if held.is_some() {
for r in &self.row_runs {
if r.fill.is_none() {
self.cov[r.x0 as usize..r.x1 as usize].fill(0);
}
}
}
#[cfg(feature = "profiling")]
{
let sweep = crate::profiling::lap_opt(&mut lap);
let c = self.prof.cur();
c.ns_aet_sweep += sweep;
c.clock_reads += 1 * prof_timed;
}
true
}
}
const SPARSE_MAX_INTERVALS: usize = 48;
const SPARSE_MIN_SPAN: usize = 64;
fn convert_row_sparse(
acc: &mut [f32],
cov: &mut [u8],
touched: &mut [(u32, u32)],
col_min: usize,
col_max: usize,
rule: FillRule,
mut runs: Option<&mut Vec<CovRun>>,
) -> (usize, usize) {
let width = cov.len();
let mut running = 0.0f32;
let mut first = width;
let mut last = 0usize;
fn push_cells(runs: &mut Option<&mut Vec<CovRun>>, x0: usize, x1: usize) {
if let Some(runs) = runs.as_deref_mut()
&& x0 < x1
{
match runs.last_mut() {
Some(prev) if prev.fill.is_none() && prev.x1 as usize == x0 => prev.x1 = x1 as u32,
_ => runs.push(CovRun {
x0: x0 as u32,
x1: x1 as u32,
fill: None,
}),
}
}
}
if touched.len() > SPARSE_MAX_INTERVALS || col_max - col_min + 1 < SPARSE_MIN_SPAN {
push_cells(&mut runs, col_min, col_max + 1);
for x in col_min..=col_max {
running += acc[x];
acc[x] = 0.0;
let byte = coverage_byte(running, rule);
cov[x] = byte;
if byte != 0 {
first = first.min(x);
last = x;
}
}
acc[col_max + 1] = 0.0;
return (first, last);
}
touched.sort_unstable_by_key(|range| range.0);
let convert_end = col_max + 1;
let mut x = col_min;
let mut i = 0;
while i < touched.len() {
let (start, mut end) = touched[i];
i += 1;
while i < touched.len() && touched[i].0 <= end {
end = end.max(touched[i].1);
i += 1;
}
let start = (start as usize).max(x);
let end = end as usize;
if start > x {
let byte = coverage_byte(running, rule);
if byte != 0 {
match runs.as_deref_mut() {
Some(runs) => runs.push(CovRun {
x0: x as u32,
x1: start as u32,
fill: Some(byte),
}),
None => cov[x..start].fill(byte),
}
first = first.min(x);
last = start - 1;
}
x = start;
}
let stop = end.min(convert_end);
push_cells(&mut runs, x, stop);
while x < stop {
running += acc[x];
acc[x] = 0.0;
let byte = coverage_byte(running, rule);
cov[x] = byte;
if byte != 0 {
first = first.min(x);
last = x;
}
x += 1;
}
for cell in &mut acc[stop..end] {
*cell = 0.0;
}
}
if x < convert_end {
let byte = coverage_byte(running, rule);
if byte != 0 {
match runs {
Some(runs) => runs.push(CovRun {
x0: x as u32,
x1: convert_end as u32,
fill: Some(byte),
}),
None => cov[x..convert_end].fill(byte),
}
first = first.min(x);
last = col_max;
}
}
acc[col_max + 1] = 0.0;
(first, last)
}
#[inline]
fn coverage_use_avx2() -> bool {
#[cfg(target_arch = "x86_64")]
{
is_x86_feature_detected!("avx2")
}
#[cfg(not(target_arch = "x86_64"))]
{
false
}
}
#[inline]
#[allow(
unsafe_code,
reason = "dispatches the AVX2 coverage kernel behind a runtime probe; see SAFETY comment"
)]
fn convert_coverage(running: &[f32], cov: &mut [u8], dst_start: usize, rule: FillRule) {
let dst = &mut cov[dst_start..dst_start + running.len()];
#[cfg(target_arch = "x86_64")]
{
if is_x86_feature_detected!("avx2") {
unsafe {
convert_coverage_avx2(running, dst, rule);
}
return;
}
}
convert_coverage_scalar(running, dst, rule);
}
#[inline]
fn convert_coverage_scalar(running: &[f32], cov: &mut [u8], rule: FillRule) {
for (i, &r) in running.iter().enumerate() {
cov[i] = coverage_byte(r, rule);
}
}
#[inline(always)]
fn coverage_byte(running: f32, rule: FillRule) -> u8 {
let c = match rule {
FillRule::NonZero => running.abs().min(1.0),
FillRule::EvenOdd => {
let m = running - 2.0 * (running * 0.5).floor();
if m > 1.0 { 2.0 - m } else { m }
}
};
(c * 255.0 + 0.5) as u8
}
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
#[allow(unsafe_code)]
unsafe fn convert_coverage_avx2(running: &[f32], cov: &mut [u8], rule: FillRule) {
use core::arch::x86_64::*;
let n = running.len();
debug_assert!(
cov.len() >= n,
"convert_coverage_avx2: destination {} shorter than {n} coverage values",
cov.len()
);
let sign = _mm256_set1_ps(-0.0);
let one = _mm256_set1_ps(1.0);
let two = _mm256_set1_ps(2.0);
let half = _mm256_set1_ps(0.5);
let s255 = _mm256_set1_ps(255.0);
let mut i = 0usize;
while i + 8 <= n {
let r = unsafe { _mm256_loadu_ps(running.as_ptr().add(i)) };
let c = match rule {
FillRule::NonZero => {
let a = _mm256_andnot_ps(sign, r);
_mm256_min_ps(a, one)
}
FillRule::EvenOdd => {
let h = _mm256_mul_ps(r, half);
let fh = _mm256_floor_ps(h);
let m = _mm256_sub_ps(r, _mm256_mul_ps(two, fh));
let gt = _mm256_cmp_ps::<_CMP_GT_OQ>(m, one);
_mm256_blendv_ps(m, _mm256_sub_ps(two, m), gt)
}
};
let scaled = _mm256_add_ps(_mm256_mul_ps(c, s255), half);
let ints = _mm256_cvttps_epi32(scaled);
let lo = _mm256_castsi256_si128(ints);
let hi = _mm256_extracti128_si256::<1>(ints);
let p16 = _mm_packus_epi32(lo, hi); let p8 = _mm_packus_epi16(p16, p16); let bytes = _mm_cvtsi128_si64(p8) as u64;
unsafe {
let dst = cov.as_mut_ptr().add(i);
core::ptr::copy_nonoverlapping(&bytes as *const u64 as *const u8, dst, 8);
}
i += 8;
}
while i < n {
unsafe {
*cov.get_unchecked_mut(i) = coverage_byte(*running.get_unchecked(i), rule);
}
i += 1;
}
}
#[allow(clippy::too_many_arguments)]
#[inline]
fn deposit_edge_row(
acc: &mut [f32],
base: usize,
xa: f32,
ya: f32,
xb: f32,
yb: f32,
dir: f32,
width: f32,
bx: usize,
stride: usize,
col_min: &mut u32,
col_max: &mut u32,
) {
let xa = xa.clamp(0.0, width);
let xb = xb.clamp(0.0, width);
let cover_total = (yb - ya) * dir;
let (x0, x1) = if xa <= xb { (xa, xb) } else { (xb, xa) };
let span = x1 - x0;
if span < 1e-9 {
deposit_local(
acc,
base,
x0.floor(),
cover_total,
x0,
width,
bx,
stride,
col_min,
col_max,
);
return;
}
let cover_per_x = cover_total / span;
let mut c = x0.floor();
while c < x1 - 1e-9 {
let lo = c.max(x0);
let hi = (c + 1.0).min(x1);
if hi > lo {
let cover_sub = cover_per_x * (hi - lo);
let xmid = 0.5 * (lo + hi);
deposit_local(
acc, base, c, cover_sub, xmid, width, bx, stride, col_min, col_max,
);
}
c += 1.0;
}
}
#[allow(clippy::too_many_arguments)]
#[inline]
fn deposit_local(
acc: &mut [f32],
base: usize,
col: f32,
cover: f32,
xmid: f32,
width: f32,
bx: usize,
stride: usize,
col_min: &mut u32,
col_max: &mut u32,
) {
let c = col.clamp(0.0, width - 1.0) as usize;
let this_px = cover * ((c as f32 + 1.0) - xmid);
let lc = c.saturating_sub(bx).min(stride - 2);
acc[base + lc] += this_px;
acc[base + lc + 1] += cover - this_px;
if (lc as u32) < *col_min {
*col_min = lc as u32;
}
if (lc as u32) > *col_max {
*col_max = lc as u32;
}
}
#[allow(clippy::too_many_arguments)]
#[inline]
fn accumulate(
acc: &mut [f32],
xa: f32,
ya: f32,
xb: f32,
yb: f32,
dir: f32,
width: f32,
col_min: &mut usize,
col_max: &mut usize,
) {
let xa = xa.clamp(0.0, width);
let xb = xb.clamp(0.0, width);
let cover_total = (yb - ya) * dir;
let (x0, x1) = if xa <= xb { (xa, xb) } else { (xb, xa) };
let span = x1 - x0;
if span < 1e-9 {
deposit_partial(acc, x0.floor(), cover_total, x0, width, col_min, col_max);
return;
}
let cover_per_x = cover_total / span;
let mut c = x0.floor();
while c < x1 - 1e-9 {
let lo = c.max(x0);
let hi = (c + 1.0).min(x1);
if hi > lo {
let cover_sub = cover_per_x * (hi - lo);
let xmid = 0.5 * (lo + hi);
deposit_partial(acc, c, cover_sub, xmid, width, col_min, col_max);
}
c += 1.0;
}
}
#[inline]
fn deposit_partial(
acc: &mut [f32],
col: f32,
cover: f32,
xmid: f32,
width: f32,
col_min: &mut usize,
col_max: &mut usize,
) {
let c = col.clamp(0.0, width - 1.0) as usize;
let this_px = cover * ((c as f32 + 1.0) - xmid);
acc[c] += this_px;
acc[c + 1] += cover - this_px;
*col_min = (*col_min).min(c);
*col_max = (*col_max).max(c);
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
fn coverage_grid(
points: &[[f32; 2]],
subpaths: &[(usize, usize)],
w: usize,
h: usize,
rule: FillRule,
) -> Vec<u8> {
let mut grid = vec![0u8; w * h];
let mut k = RasterKernel::default();
k.fill(points, subpaths, w, h, rule, |y, x0, x1, cov: &mut [u8]| {
grid[y * w + x0..y * w + x1 + 1].copy_from_slice(&cov[x0..=x1]);
});
grid
}
fn coverage_grid_ref(
points: &[[f32; 2]],
subpaths: &[(usize, usize)],
w: usize,
h: usize,
rule: FillRule,
) -> Vec<u8> {
let mut grid = vec![0u8; w * h];
let mut k = RasterKernel::default();
k.run_reference(points, subpaths, w, h, rule, |y, x0, x1, cov: &mut [u8]| {
grid[y * w + x0..y * w + x1 + 1].copy_from_slice(&cov[x0..=x1]);
});
grid
}
fn coverage_grid_aet(
points: &[[f32; 2]],
subpaths: &[(usize, usize)],
w: usize,
h: usize,
rule: FillRule,
) -> Vec<u8> {
let mut grid = vec![0u8; w * h];
let mut k = RasterKernel::default();
k.run_aet(points, subpaths, w, h, rule, |y, x0, x1, cov: &mut [u8]| {
grid[y * w + x0..y * w + x1 + 1].copy_from_slice(&cov[x0..=x1]);
});
grid
}
type Geometry = (Vec<[f32; 2]>, Vec<(usize, usize)>);
fn rect(x0: f32, y0: f32, x1: f32, y1: f32) -> Geometry {
(vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]], vec![(0, 4)])
}
#[test]
fn integer_rect_is_exact() {
let (p, s) = rect(1.0, 1.0, 3.0, 3.0);
let g = coverage_grid(&p, &s, 4, 4, FillRule::NonZero);
for y in 0..4 {
for x in 0..4 {
let expected = if (1..3).contains(&x) && (1..3).contains(&y) {
255
} else {
0
};
assert_eq!(g[y * 4 + x], expected, "pixel ({x},{y})");
}
}
}
#[test]
fn cancellable_fill_stops_inside_one_path_and_resets_worker_scratch() {
use std::sync::atomic::{AtomicUsize, Ordering};
let (points, subpaths) = rect(0.0, 0.0, 128.0, 4096.0);
let checks = AtomicUsize::new(0);
let cancel = || checks.fetch_add(1, Ordering::Relaxed) >= 2;
let mut rows = 0usize;
let mut kernel = RasterKernel::default();
let completed = kernel.fill_cancellable(
&points,
&subpaths,
128,
4096,
FillRule::NonZero,
Some(&cancel),
|_, _, _, _| rows += 1,
);
assert!(!completed, "the single long fill must observe cancellation");
assert!(rows < 4096, "cancellation must stop before page completion");
let mut recovered = vec![0u8; 4];
let (small_points, small_subpaths) = rect(0.0, 0.0, 2.0, 2.0);
kernel.fill(
&small_points,
&small_subpaths,
2,
2,
FillRule::NonZero,
|y, x0, x1, cov| {
recovered[y * 2 + x0..=y * 2 + x1].copy_from_slice(&cov[x0..=x1]);
},
);
assert_eq!(recovered, vec![255; 4]);
}
#[test]
fn a_fill_after_an_unwound_fill_matches_a_fresh_kernel() {
let grid = |kernel: &mut RasterKernel, g: &Geometry, w: usize, h: usize| {
let mut out = vec![0u8; w * h];
kernel.fill(&g.0, &g.1, w, h, FillRule::NonZero, |y, x0, x1, cov| {
out[y * w + x0..=y * w + x1].copy_from_slice(&cov[x0..=x1]);
});
out
};
let cases: [(usize, usize, Geometry, Geometry); 2] = [
(
48,
48,
(vec![[1.3, 0.7], [46.2, 3.1], [20.5, 47.4]], vec![(0, 3)]),
rect(4.25, 4.75, 40.5, 41.0),
),
(
1193,
24,
(vec![[0.4, 0.2], [1192.7, 11.3], [3.1, 23.9]], vec![(0, 3)]),
rect(2.0, 5.5, 1150.0, 6.0),
),
];
for (w, h, first, second) in cases {
let want = grid(&mut RasterKernel::default(), &second, w, h);
let mut kernel = RasterKernel::default();
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let mut rows = 0;
kernel.fill(&first.0, &first.1, w, h, FillRule::NonZero, |_, _, _, _| {
rows += 1;
if rows == 3 {
panic!("synthetic panic inside a fill");
}
});
}));
assert!(unwound.is_err());
let got = grid(&mut kernel, &second, w, h);
assert!(
got == want,
"{w}x{h}: the fill after an unwound fill differs from a fresh kernel's"
);
}
}
#[test]
fn half_pixel_horizontal_is_exact() {
let (p, s) = rect(0.0, 0.0, 0.5, 2.0);
let g = coverage_grid(&p, &s, 2, 2, FillRule::NonZero);
for y in 0..2 {
assert!(
(g[y * 2] as i32 - 128).abs() <= 1,
"left col row {y} = {}",
g[y * 2]
);
assert_eq!(g[y * 2 + 1], 0);
}
}
#[test]
fn half_pixel_vertical_is_exact() {
let (p, s) = rect(0.0, 0.0, 2.0, 0.5);
let g = coverage_grid(&p, &s, 2, 2, FillRule::NonZero);
assert!((g[0] as i32 - 128).abs() <= 1, "row0 = {}", g[0]);
assert_eq!(g[2], 0, "row1 uncovered");
}
#[test]
fn even_odd_hole() {
let mut p = vec![[0.0, 0.0], [6.0, 0.0], [6.0, 6.0], [0.0, 6.0]];
p.extend_from_slice(&[[2.0, 2.0], [4.0, 2.0], [4.0, 4.0], [2.0, 4.0]]);
let s = vec![(0, 4), (4, 8)];
let g = coverage_grid(&p, &s, 6, 6, FillRule::EvenOdd);
assert_eq!(g[3 * 6 + 3], 0, "hole center");
assert_eq!(g[3 * 6 + 1], 255, "ring pixel");
}
#[test]
fn nonzero_overlap_saturates() {
let mut p = vec![[0.0, 0.0], [3.0, 0.0], [3.0, 3.0], [0.0, 3.0]];
p.extend_from_slice(&[[1.0, 0.0], [4.0, 0.0], [4.0, 3.0], [1.0, 3.0]]);
let s = vec![(0, 4), (4, 8)];
let g = coverage_grid(&p, &s, 4, 3, FillRule::NonZero);
assert_eq!(g[2], 255, "overlap column stays 255");
}
#[test]
fn triangle_area_matches() {
let p = vec![[0.0, 0.0], [4.0, 0.0], [0.0, 4.0]];
let s = vec![(0, 3)];
let g = coverage_grid(&p, &s, 4, 4, FillRule::NonZero);
let total: f32 = g.iter().map(|&b| b as f32 / 255.0).sum();
assert!((total - 8.0).abs() < 0.1, "area ~= {total}");
}
struct Lcg(u64);
impl Lcg {
fn next_u32(&mut self) -> u32 {
self.0 = self
.0
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
(self.0 >> 33) as u32
}
fn f(&mut self, lo: f32, hi: f32) -> f32 {
lo + (self.next_u32() as f32 / u32::MAX as f32) * (hi - lo)
}
}
fn random_path(rng: &mut Lcg, w: f32, h: f32) -> (Vec<[f32; 2]>, Vec<(usize, usize)>) {
let mut pts = Vec::new();
let mut subs = Vec::new();
let nsub = 1 + (rng.next_u32() % 3) as usize;
for _ in 0..nsub {
let start = pts.len();
let nv = 3 + (rng.next_u32() % 6) as usize;
for _ in 0..nv {
pts.push([rng.f(-2.0, w + 2.0), rng.f(-2.0, h + 2.0)]);
}
subs.push((start, pts.len()));
}
(pts, subs)
}
#[test]
fn fast_path_matches_reference_bit_exact() {
let mut rng = Lcg(0xC0FFEE_1234_5678);
for w in [1usize, 3, 8, 17, 40, 128] {
for h in [1usize, 3, 8, 17, 40, 96] {
for rule in [FillRule::NonZero, FillRule::EvenOdd] {
for _ in 0..40 {
let (p, s) = random_path(&mut rng, w as f32, h as f32);
let fast = coverage_grid(&p, &s, w, h, rule);
let refr = coverage_grid_ref(&p, &s, w, h, rule);
assert_eq!(
fast, refr,
"fast vs reference mismatch at {w}x{h} rule {rule:?}"
);
}
}
}
}
}
#[test]
fn aet_matches_reference_bit_exact() {
let mut rng = Lcg(0x5EED_A57_9911_2244);
for w in [1usize, 3, 8, 17, 40, 128] {
for h in [1usize, 3, 8, 17, 40, 96] {
for rule in [FillRule::NonZero, FillRule::EvenOdd] {
for _ in 0..40 {
let (p, s) = random_path(&mut rng, w as f32, h as f32);
let aet = coverage_grid_aet(&p, &s, w, h, rule);
let refr = coverage_grid_ref(&p, &s, w, h, rule);
assert_eq!(
aet, refr,
"aet vs reference mismatch at {w}x{h} rule {rule:?}"
);
}
}
}
}
}
#[test]
fn aet_sparse_rows_match_dense() {
let w = 1193usize;
let h = 24usize;
let mut cases: Vec<Geometry> = vec![
rect(0.0, 0.0, w as f32, h as f32),
rect(0.37, 0.61, 1190.91, 23.4),
rect(-5.0, -3.0, 1300.0, 40.0),
rect(3.0, 2.0, 1100.0, 20.0),
rect(3.5, 2.0, 4.2, 20.0), (
vec![
[1.3, 1.2],
[1191.7, 1.2],
[1191.7, 22.8],
[1.3, 22.8],
[3.3, 3.2],
[3.3, 20.8],
[1189.7, 20.8],
[1189.7, 3.2],
],
vec![(0, 4), (4, 8)],
),
(
vec![
[10.0, 2.5],
[300.5, 2.5],
[300.5, 21.5],
[10.0, 21.5],
[700.25, 4.0],
[1180.0, 4.0],
[1180.0, 19.0],
[700.25, 19.0],
],
vec![(0, 4), (4, 8)],
),
(vec![[0.0, 0.0], [1193.0, 24.0], [0.0, 24.0]], vec![(0, 3)]),
];
let mut rng = Lcg(0x5A5A_1234_8765_4321);
for _ in 0..60 {
cases.push(random_path(&mut rng, w as f32, h as f32));
}
for (p, s) in &cases {
for rule in [FillRule::NonZero, FillRule::EvenOdd] {
let aet = coverage_grid_aet(p, s, w, h, rule);
let refr = coverage_grid_ref(p, s, w, h, rule);
assert_eq!(aet, refr, "sparse AET vs reference mismatch, rule {rule:?}");
let prod = coverage_grid(p, s, w, h, rule);
assert_eq!(prod, refr, "fill vs reference mismatch, rule {rule:?}");
}
}
}
#[test]
fn fill_runs_match_fill() {
let w = 1193usize;
let h = 24usize;
let mut cases: Vec<Geometry> = vec![
rect(0.0, 0.0, w as f32, h as f32),
rect(0.37, 0.61, 1190.91, 23.4),
rect(-5.0, -3.0, 1300.0, 40.0),
rect(3.5, 2.0, 4.2, 20.0),
(
vec![
[1.3, 1.2],
[1191.7, 1.2],
[1191.7, 22.8],
[1.3, 22.8],
[3.3, 3.2],
[3.3, 20.8],
[1189.7, 20.8],
[1189.7, 3.2],
],
vec![(0, 4), (4, 8)],
),
(
vec![
[10.0, 2.5],
[900.5, 2.5],
[900.5, 21.5],
[10.0, 21.5],
[300.25, 4.0],
[1180.0, 4.0],
[1180.0, 19.0],
[300.25, 19.0],
],
vec![(0, 4), (4, 8)],
),
rect(2.0, 5.5, 1150.0, 6.0),
(vec![[0.0, 0.0], [1193.0, 24.0], [0.0, 24.0]], vec![(0, 3)]),
rect(3.25, 2.5, 40.75, 9.5),
(
vec![
[0.5, 0.0],
[1192.5, 0.0],
[1192.5, 24.0],
[0.5, 24.0],
[100.0, 5.0],
[600.0, 5.0],
[600.0, 12.3],
[100.0, 12.3],
[700.7, 9.0],
[701.2, 9.0],
[701.2, 17.0],
[700.7, 17.0],
],
vec![(0, 4), (4, 8), (8, 12)],
),
(
vec![
[2.0, 1.0],
[1100.0, 1.0],
[1100.0, 23.0],
[2.0, 23.0],
[300.0, 6.0],
[340.0, 14.0],
[320.0, 14.0],
],
vec![(0, 4), (4, 7)],
),
];
let mut rng = Lcg(0x0BAD_C0DE_1357_9BDF);
for _ in 0..40 {
cases.push(random_path(&mut rng, w as f32, h as f32));
}
for materialize in [false, true] {
let mut k = RasterKernel::default();
for (p, s) in &cases {
for rule in [FillRule::NonZero, FillRule::EvenOdd] {
let expect = coverage_grid(p, s, w, h, rule);
let mut grid = vec![0u8; w * h];
let mut spans = Vec::new();
k.fill_runs_cancellable(p, s, w, h, rule, None, |y, x0, x1, cov, runs| {
spans.push((y, x0, x1));
let mut prev_end = 0u32;
for r in runs {
assert!(r.x0 < r.x1 && r.x0 >= prev_end, "runs ordered: {runs:?}");
prev_end = r.x1;
let row = &mut grid[y * w..(y + 1) * w];
match r.fill {
None => row[r.x0 as usize..r.x1 as usize]
.copy_from_slice(&cov[r.x0 as usize..r.x1 as usize]),
Some(c) => {
assert!(
cov[r.x0 as usize..r.x1 as usize].iter().all(|&b| b == 0),
"constant run written into the buffer"
);
row[r.x0 as usize..r.x1 as usize].fill(c);
}
}
}
if materialize {
for r in runs {
if let Some(c) = r.fill {
cov[r.x0 as usize..r.x1 as usize].fill(c);
}
}
}
materialize
});
assert_eq!(
grid, expect,
"runs vs fill, rule {rule:?} materialize {materialize}"
);
let mut plain = Vec::new();
RasterKernel::default()
.fill(p, s, w, h, rule, |y, x0, x1, _| plain.push((y, x0, x1)));
assert_eq!(spans, plain, "row spans, rule {rule:?}");
}
}
}
}
#[test]
fn aet_matches_reference_on_edge_cases() {
let cases: Vec<Geometry> = vec![
rect(1.0, 2.0, 5.0, 6.0), rect(0.5, 2.3, 4.5, 5.7), rect(-3.0, -2.0, 4.0, 5.0), rect(2.0, 0.0, 3.0, 8.0), (vec![[1.0, 1.5], [7.0, 1.5], [4.0, 6.5]], vec![(0, 3)]), ];
let mut many = Vec::new();
let mut subs = Vec::new();
for k in 0..500u32 {
let x = 0.1 + (k as f32) * 0.01;
let base = many.len();
many.extend_from_slice(&[[x, 0.2], [x + 0.005, 0.2], [x + 0.005, 7.8], [x, 7.8]]);
subs.push((base, base + 4));
}
let mut all = cases;
all.push((many, subs));
for (p, s) in &all {
for rule in [FillRule::NonZero, FillRule::EvenOdd] {
let aet = coverage_grid_aet(p, s, 8, 8, rule);
let refr = coverage_grid_ref(p, s, 8, 8, rule);
assert_eq!(
aet, refr,
"aet vs reference edge-case mismatch, rule {rule:?}"
);
}
}
}
#[test]
#[allow(
unsafe_code,
reason = "bit-compares the AVX2 kernel against the scalar reference; see SAFETY comment"
)]
fn avx2_convert_matches_scalar_bit_exact() {
let mut rng = Lcg(0xA5A5_0F0F_1111_2222);
let n = 8 * 200 + 5; let mut running = Vec::with_capacity(n);
for _ in 0..n {
running.push(rng.f(-8.0, 8.0));
}
for rule in [FillRule::NonZero, FillRule::EvenOdd] {
let mut a = vec![0u8; n];
let mut b = vec![0u8; n];
convert_coverage_scalar(&running, &mut a, rule);
#[cfg(target_arch = "x86_64")]
{
if is_x86_feature_detected!("avx2") {
unsafe { convert_coverage_avx2(&running, &mut b, rule) };
} else {
convert_coverage_scalar(&running, &mut b, rule);
}
}
#[cfg(not(target_arch = "x86_64"))]
convert_coverage_scalar(&running, &mut b, rule);
assert_eq!(a, b, "avx2 vs scalar coverage mismatch, rule {rule:?}");
}
}
}
#[cfg(test)]
impl RasterKernel {
#[allow(clippy::too_many_arguments)]
fn run_fallback(
&mut self,
points: &[[f32; 2]],
subpaths: &[(usize, usize)],
width: usize,
height: usize,
rule: FillRule,
row: impl FnMut(usize, usize, usize, &mut [u8]),
aet: bool,
) {
if width == 0 || height == 0 {
return;
}
if self.cov.len() < width {
self.cov.resize(width, 0);
}
self.edges.clear();
let mut y_min = f32::INFINITY;
let mut y_max = f32::NEG_INFINITY;
for &(start, end) in subpaths {
let n = end - start;
if n < 2 {
continue;
}
for i in 0..n {
let a = points[start + i];
let b = points[start + (i + 1) % n];
if a[1] == b[1] {
continue;
}
let (y_top, y_bot, x_at_top, dir) = if a[1] < b[1] {
(a[1], b[1], a[0], 1.0)
} else {
(b[1], a[1], b[0], -1.0)
};
let dxdy = (b[0] - a[0]) / (b[1] - a[1]);
self.edges.push(Edge {
y_top,
y_bot,
x_at_top,
dxdy,
dir,
});
y_min = y_min.min(y_top);
y_max = y_max.max(y_bot);
}
}
if self.edges.is_empty() {
return;
}
self.last_edges = self.edges.len() as u64;
let row_start = y_min.floor().max(0.0) as usize;
let row_end = (y_max.ceil().min(height as f32)) as usize;
self.last_rows = row_end.saturating_sub(row_start) as u64;
self.last_covered = 0;
if row_end <= row_start {
return;
}
if aet {
let mut row = row;
let _ = self.fill_scanline_aet(
width,
height,
rule,
row_start,
row_end,
row_start,
row_end,
None,
false,
|y, x0, x1, cov, _| {
row(y, x0, x1, cov);
true
},
);
} else {
self.fill_scanline_ref(width, height, rule, row_start, row_end, row);
}
}
fn run_reference(
&mut self,
points: &[[f32; 2]],
subpaths: &[(usize, usize)],
width: usize,
height: usize,
rule: FillRule,
row: impl FnMut(usize, usize, usize, &mut [u8]),
) {
self.run_fallback(points, subpaths, width, height, rule, row, false);
}
fn run_aet(
&mut self,
points: &[[f32; 2]],
subpaths: &[(usize, usize)],
width: usize,
height: usize,
rule: FillRule,
row: impl FnMut(usize, usize, usize, &mut [u8]),
) {
self.run_fallback(points, subpaths, width, height, rule, row, true);
}
}
#[cfg(test)]
mod row_window_tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::{CovRun, FillRule, RasterKernel};
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn range(&mut self, lo: f32, hi: f32) -> f32 {
lo + (hi - lo) * ((self.next() >> 40) as f32 / (1u64 << 24) as f32)
}
fn pick(&mut self, n: u64) -> u64 {
self.next() % n
}
}
type Row = (usize, usize, usize, Vec<u8>);
fn materialize(first: usize, last: usize, cov: &[u8], runs: &[CovRun]) -> Vec<u8> {
let mut bytes = vec![0u8; last - first + 1];
for run in runs {
let (x0, x1) = (
(run.x0 as usize).max(first),
(run.x1 as usize).min(last + 1),
);
if x0 >= x1 {
continue;
}
match run.fill {
Some(value) => bytes[x0 - first..x1 - first].fill(value),
None => bytes[x0 - first..x1 - first].copy_from_slice(&cov[x0..x1]),
}
}
bytes
}
#[allow(clippy::too_many_arguments)]
fn collect(
kernel: &mut RasterKernel,
points: &[[f32; 2]],
subpaths: &[(usize, usize)],
width: usize,
height: usize,
rule: FillRule,
rows: std::ops::Range<usize>,
runs_mode: bool,
) -> Vec<Row> {
let mut out: Vec<Row> = Vec::new();
if runs_mode {
assert!(kernel.fill_runs_cancellable_in(
points,
subpaths,
width,
height,
rule,
rows,
None,
|y, first, last, cov, runs| {
out.push((y, first, last, materialize(first, last, cov, runs)));
false
},
));
} else {
assert!(kernel.fill_cancellable_in(
points,
subpaths,
width,
height,
rule,
rows,
None,
|y, first, last, cov| out.push((y, first, last, cov[first..=last].to_vec())),
));
}
out
}
fn geometry(rng: &mut Rng, kind: u64, w: f32, h: f32) -> (Vec<[f32; 2]>, Vec<(usize, usize)>) {
let mut points = Vec::new();
let mut subpaths = Vec::new();
let mut polygon = |points: &mut Vec<[f32; 2]>, vertices: &[[f32; 2]]| {
let start = points.len();
points.extend_from_slice(vertices);
subpaths.push((start, points.len()));
};
match kind {
0 => {
let (cx, cy) = (rng.range(0.0, w), rng.range(0.0, h));
let n = 3 + rng.pick(6) as usize;
let vertices: Vec<[f32; 2]> = (0..n)
.map(|_| [cx + rng.range(-25.0, 25.0), cy + rng.range(-25.0, 25.0)])
.collect();
polygon(&mut points, &vertices);
}
1 => {
let n = 3 + rng.pick(3) as usize;
let vertices: Vec<[f32; 2]> = (0..n)
.map(|_| [rng.range(-40.0, w + 40.0), rng.range(-40.0, h + 40.0)])
.collect();
polygon(&mut points, &vertices);
}
2 => {
for _ in 0..(60 + rng.pick(200)) {
let (cx, cy) = (rng.range(-5.0, w + 5.0), rng.range(-5.0, h + 5.0));
let r = rng.range(0.3, 6.0);
let vertices: Vec<[f32; 2]> = (0..8)
.map(|i| {
let t = i as f32 / 8.0 * std::f32::consts::TAU;
[cx + r * t.cos(), cy + r * t.sin()]
})
.collect();
polygon(&mut points, &vertices);
}
}
4 => {
for _ in 0..(1 + rng.pick(3)) {
let wide = rng.pick(2) == 0;
let (rw, rh) = if wide {
(rng.range(20.0, w * 0.95), rng.range(0.2, 9.0))
} else {
(rng.range(0.2, 9.0), rng.range(20.0, h * 0.95))
};
let (x0, y0) = (rng.range(-5.0, w - rw), rng.range(-5.0, h - rh));
let snap = |v: f32, on: bool| if on { v.round() } else { v };
let on = rng.pick(3) == 0;
let (x0, y0, x1, y1) = (
snap(x0, on),
snap(y0, on),
snap(x0 + rw, on),
snap(y0 + rh, on),
);
polygon(&mut points, &[[x0, y0], [x1, y0], [x1, y1], [x0, y1]]);
if rng.pick(4) == 0 {
polygon(
&mut points,
&[
[x0 + 3.3, y0 - 1.0],
[x0 + 9.1, y0 - 1.0],
[x0 + 30.7, y1 + 1.0],
],
);
}
}
}
_ => {
for _ in 0..(1 + rng.pick(4)) {
let (x0, y0) = (rng.range(-10.0, w * 0.6), rng.range(-10.0, h * 0.6));
let (x1, y1) = (x0 + rng.range(1.0, w * 0.6), y0 + rng.range(1.0, h * 0.6));
let snap = |v: f32, on: bool| if on { v.round() } else { v };
let on = rng.pick(2) == 0;
let (x0, y0, x1, y1) = (snap(x0, on), snap(y0, on), snap(x1, on), snap(y1, on));
polygon(&mut points, &[[x0, y0], [x1, y0], [x1, y1], [x0, y1]]);
}
}
}
(points, subpaths)
}
#[test]
fn windowed_fill_equals_the_same_rows_of_a_full_fill() {
let mut rng = Rng(0x2545_f491_4f6c_dd1d);
let (width, height) = (700usize, 420usize);
let mut kernel = RasterKernel::default();
let mut reference_kernel = RasterKernel::default();
let mut nonempty = 0;
for case in 0..500 {
let kind = case % 5;
let (points, subpaths) = geometry(&mut rng, kind, width as f32, height as f32);
let rule = if rng.pick(2) == 0 {
FillRule::NonZero
} else {
FillRule::EvenOdd
};
let runs_mode = rng.pick(2) == 0;
let full = collect(
&mut reference_kernel,
&points,
&subpaths,
width,
height,
rule,
0..usize::MAX,
runs_mode,
);
let other_mode = collect(
&mut reference_kernel,
&points,
&subpaths,
width,
height,
rule,
0..usize::MAX,
!runs_mode,
);
assert!(
full == other_mode,
"case {case} kind {kind}: runs and bytes disagree"
);
let a = rng.pick(height as u64 + 40) as usize;
let b = a + rng.pick(height as u64 / 2 + 2) as usize;
for rows in [a..b, 0..a, a..usize::MAX, b..b, 0..usize::MAX] {
let expected: Vec<Row> = full
.iter()
.filter(|row| rows.contains(&row.0))
.cloned()
.collect();
let got = collect(
&mut kernel,
&points,
&subpaths,
width,
height,
rule,
rows.clone(),
runs_mode,
);
assert!(
got == expected,
"case {case} kind {kind} rows {rows:?} runs_mode {runs_mode}: {} rows vs {}",
got.len(),
expected.len()
);
if !got.is_empty() && got.len() < full.len() {
nonempty += 1;
}
}
}
assert!(
nonempty > 400,
"only {nonempty} windows actually restricted a fill"
);
}
}