use std::sync::{Arc, Mutex, Weak};
use crate::page_ir::{
DeviceRect, ImageColorSpace, ImageMask, ImageSMask, InterpolationMode, Matrix, Point,
};
use crate::render_api::{CancellationToken, RenderError};
use crate::render_cpu::surface::{filled_arc, unique_arc_mut, zeroed_arc};
#[derive(Debug)]
pub(crate) struct SharedRgbImageCache {
state: Mutex<RgbImageCacheState>,
budget_bytes: usize,
}
#[derive(Debug, Default)]
struct RgbImageCacheState {
entries: Vec<RgbImageCacheEntry>,
bytes: usize,
clock: u64,
}
#[derive(Debug)]
struct RgbImageCacheEntry {
source: Weak<[u8]>,
width: u32,
height: u32,
bpc: u8,
color_space: ImageColorSpace,
decode: Option<Arc<[[f32; 2]]>>,
rgb: Arc<[u8]>,
charge: usize,
last_used: u64,
}
impl SharedRgbImageCache {
const DEFAULT_BUDGET_BYTES: usize = crate::render_cpu::MAX_PREPARED_RGB_CONVERSION_BYTES;
pub(crate) fn new(budget_bytes: usize) -> Self {
Self {
state: Mutex::new(RgbImageCacheState::default()),
budget_bytes,
}
}
pub(crate) fn get_or_convert(
&self,
image: &PreparedImage,
cancellation: Option<&CancellationToken>,
) -> Result<Option<Arc<[u8]>>, RenderError> {
if image.is_direct_rgb8() {
return Ok(Some(Arc::clone(&image.samples)));
}
let Some(rgb_len) = image.rgb8_len() else {
return Ok(None);
};
if rgb_len > self.budget_bytes {
return Ok(None);
}
if let Some(rgb) = self.lookup(image) {
return Ok(Some(rgb));
}
let mut converted = zeroed_arc(rgb_len);
let width = image.width as usize;
let converted_data = unique_arc_mut(&mut converted);
for row in 0..image.height {
if row % 32 == 0 && cancellation.is_some_and(CancellationToken::is_cancelled) {
return Err(RenderError::Cancelled);
}
for col in 0..image.width {
let rgba = image
.source_pixel(col, row)
.ok_or(RenderError::Unsupported(
crate::page_ir::PageFeatures::IMAGES,
))?;
let offset = (row as usize * width + col as usize) * 3;
converted_data[offset..offset + 3].copy_from_slice(&rgba[..3]);
}
}
if cancellation.is_some_and(CancellationToken::is_cancelled) {
return Err(RenderError::Cancelled);
}
if let Some(rgb) = self.lookup(image) {
return Ok(Some(rgb));
}
self.insert(image, Arc::clone(&converted));
Ok(Some(converted))
}
fn lookup(&self, image: &PreparedImage) -> Option<Arc<[u8]>> {
let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
state.clock = state.clock.wrapping_add(1);
let clock = state.clock;
let mut hit = None;
let mut removed_bytes = 0usize;
state.entries.retain_mut(|entry| {
let Some(source) = entry.source.upgrade() else {
removed_bytes = removed_bytes.saturating_add(entry.charge);
return false;
};
if hit.is_none()
&& Arc::ptr_eq(&source, &image.samples)
&& entry.width == image.width
&& entry.height == image.height
&& entry.bpc == image.bpc
&& entry.color_space == image.color_space
&& entry.decode == image.decode
{
entry.last_used = clock;
hit = Some(Arc::clone(&entry.rgb));
}
true
});
state.bytes = state.bytes.saturating_sub(removed_bytes);
hit
}
fn insert(&self, image: &PreparedImage, rgb: Arc<[u8]>) {
let charge = rgb.len() + std::mem::size_of::<RgbImageCacheEntry>();
let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
state.clock = state.clock.wrapping_add(1);
let clock = state.clock;
state.entries.push(RgbImageCacheEntry {
source: Arc::downgrade(&image.samples),
width: image.width,
height: image.height,
bpc: image.bpc,
color_space: image.color_space.clone(),
decode: image.decode.clone(),
rgb,
charge,
last_used: clock,
});
state.bytes += charge;
while state.bytes > self.budget_bytes && state.entries.len() > 1 {
let victim = state
.entries
.iter()
.enumerate()
.min_by_key(|(_, entry)| entry.last_used)
.map(|(index, _)| index)
.unwrap_or(0);
let removed = state.entries.swap_remove(victim);
state.bytes = state.bytes.saturating_sub(removed.charge);
}
}
}
impl Default for SharedRgbImageCache {
fn default() -> Self {
Self::new(Self::DEFAULT_BUDGET_BYTES)
}
}
#[derive(Debug)]
pub(crate) struct SharedOpacityImageCache {
state: Mutex<OpacityImageCacheState>,
budget_bytes: usize,
}
#[derive(Debug, Default)]
struct OpacityImageCacheState {
entries: Vec<OpacityImageCacheEntry>,
bytes: usize,
clock: u64,
}
#[derive(Debug)]
struct OpacityImageCacheEntry {
source: Weak<[u8]>,
width: u32,
height: u32,
bpc: u8,
decode: Option<Arc<[[f32; 2]]>>,
inverted: bool,
components: u8,
color_key: Option<Arc<[[u32; 2]]>>,
alpha: Arc<[u8]>,
charge: usize,
last_used: u64,
}
impl SharedOpacityImageCache {
pub(crate) fn new(budget_bytes: usize) -> Self {
Self {
state: Mutex::new(OpacityImageCacheState::default()),
budget_bytes,
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn get_or_expand(
&self,
source: &Arc<[u8]>,
width: u32,
height: u32,
bpc: u8,
decode: Option<&Arc<[[f32; 2]]>>,
inverted: bool,
cancellation: Option<&CancellationToken>,
) -> Result<Option<Arc<[u8]>>, RenderError> {
if !(1..=16).contains(&bpc) {
return Ok(None);
}
let Some(alpha_len) = (width as usize).checked_mul(height as usize) else {
return Ok(None);
};
if alpha_len == 0 || alpha_len > self.budget_bytes {
return Ok(None);
}
if let Some(alpha) = self.lookup(source, width, height, bpc, decode, inverted, 1, None) {
return Ok(Some(alpha));
}
let row_bits = (width as usize * bpc as usize).div_ceil(8) * 8;
let max_value = ((1u64 << bpc) - 1) as f32;
let decode_pair = decode.and_then(|pairs| pairs.first()).copied();
let mut expanded = zeroed_arc(alpha_len);
let expanded_data = unique_arc_mut(&mut expanded);
for row in 0..height {
if row % 32 == 0 && cancellation.is_some_and(CancellationToken::is_cancelled) {
return Err(RenderError::Cancelled);
}
for column in 0..width {
let bit = row as usize * row_bits + column as usize * bpc as usize;
let raw = read_bits(source, bit, bpc as usize) as f32 / max_value;
let decoded = match decode_pair {
Some([lo, hi]) => lo + raw * (hi - lo),
None => raw,
}
.clamp(0.0, 1.0);
let opacity = if inverted { 1.0 - decoded } else { decoded };
expanded_data[row as usize * width as usize + column as usize] = to_u8(opacity);
}
}
if cancellation.is_some_and(CancellationToken::is_cancelled) {
return Err(RenderError::Cancelled);
}
if let Some(alpha) = self.lookup(source, width, height, bpc, decode, inverted, 1, None) {
return Ok(Some(alpha));
}
self.insert(
source,
width,
height,
bpc,
decode.cloned(),
inverted,
1,
None,
Arc::clone(&expanded),
);
Ok(Some(expanded))
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn get_or_expand_color_key(
&self,
source: &Arc<[u8]>,
width: u32,
height: u32,
bpc: u8,
components: usize,
ranges: &Arc<[[u32; 2]]>,
cancellation: Option<&CancellationToken>,
) -> Result<Option<Arc<[u8]>>, RenderError> {
if !(1..=16).contains(&bpc)
|| components == 0
|| components > u8::MAX as usize
|| ranges.len() != components
{
return Ok(None);
}
let Some(alpha_len) = (width as usize).checked_mul(height as usize) else {
return Ok(None);
};
if alpha_len == 0 || alpha_len > self.budget_bytes {
return Ok(None);
}
let components = components as u8;
if let Some(alpha) = self.lookup(
source,
width,
height,
bpc,
None,
false,
components,
Some(ranges),
) {
return Ok(Some(alpha));
}
let Some(row_sample_bits) = (width as usize)
.checked_mul(components as usize)
.and_then(|samples| samples.checked_mul(bpc as usize))
else {
return Ok(None);
};
let row_bits = row_sample_bits.div_ceil(8) * 8;
let Some(source_bytes) = row_bits
.checked_div(8)
.and_then(|bytes| bytes.checked_mul(height as usize))
else {
return Ok(None);
};
if source.len() < source_bytes {
return Ok(None);
}
let mut expanded = filled_arc(alpha_len, 255);
let expanded_data = unique_arc_mut(&mut expanded);
for row in 0..height {
if row % 32 == 0 && cancellation.is_some_and(CancellationToken::is_cancelled) {
return Err(RenderError::Cancelled);
}
for column in 0..width {
let pixel_bit =
row as usize * row_bits + column as usize * components as usize * bpc as usize;
let masked = ranges.iter().enumerate().all(|(component, &[lo, hi])| {
let bit = pixel_bit + component * bpc as usize;
let raw = read_bits(source, bit, bpc as usize);
raw >= lo && raw <= hi
});
if masked {
expanded_data[row as usize * width as usize + column as usize] = 0;
}
}
}
if cancellation.is_some_and(CancellationToken::is_cancelled) {
return Err(RenderError::Cancelled);
}
if let Some(alpha) = self.lookup(
source,
width,
height,
bpc,
None,
false,
components,
Some(ranges),
) {
return Ok(Some(alpha));
}
self.insert(
source,
width,
height,
bpc,
None,
false,
components,
Some(Arc::clone(ranges)),
Arc::clone(&expanded),
);
Ok(Some(expanded))
}
#[allow(clippy::too_many_arguments)]
fn lookup(
&self,
source: &Arc<[u8]>,
width: u32,
height: u32,
bpc: u8,
decode: Option<&Arc<[[f32; 2]]>>,
inverted: bool,
components: u8,
color_key: Option<&Arc<[[u32; 2]]>>,
) -> Option<Arc<[u8]>> {
let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
state.clock = state.clock.wrapping_add(1);
let clock = state.clock;
let mut hit = None;
let mut removed_bytes = 0usize;
state.entries.retain_mut(|entry| {
let Some(cached_source) = entry.source.upgrade() else {
removed_bytes = removed_bytes.saturating_add(entry.charge);
return false;
};
if hit.is_none()
&& Arc::ptr_eq(&cached_source, source)
&& entry.width == width
&& entry.height == height
&& entry.bpc == bpc
&& entry.decode.as_ref() == decode
&& entry.inverted == inverted
&& entry.components == components
&& entry.color_key.as_ref() == color_key
{
entry.last_used = clock;
hit = Some(Arc::clone(&entry.alpha));
}
true
});
state.bytes = state.bytes.saturating_sub(removed_bytes);
hit
}
#[allow(clippy::too_many_arguments)]
fn insert(
&self,
source: &Arc<[u8]>,
width: u32,
height: u32,
bpc: u8,
decode: Option<Arc<[[f32; 2]]>>,
inverted: bool,
components: u8,
color_key: Option<Arc<[[u32; 2]]>>,
alpha: Arc<[u8]>,
) {
let charge = alpha.len() + std::mem::size_of::<OpacityImageCacheEntry>();
let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
state.clock = state.clock.wrapping_add(1);
let clock = state.clock;
state.entries.push(OpacityImageCacheEntry {
source: Arc::downgrade(source),
width,
height,
bpc,
decode,
inverted,
components,
color_key,
alpha,
charge,
last_used: clock,
});
state.bytes += charge;
while state.bytes > self.budget_bytes && state.entries.len() > 1 {
let victim = state
.entries
.iter()
.enumerate()
.min_by_key(|(_, entry)| entry.last_used)
.map(|(index, _)| index)
.unwrap_or(0);
let removed = state.entries.swap_remove(victim);
state.bytes = state.bytes.saturating_sub(removed.charge);
}
}
}
impl Default for SharedOpacityImageCache {
fn default() -> Self {
Self::new(crate::render_cpu::MAX_PREPARED_OPACITY_CONVERSION_BYTES)
}
}
#[derive(Debug, Clone)]
pub struct PreparedImage {
pub origin: crate::page_ir::PaintOrigin,
pub bounds: DeviceRect,
pub clip: Option<u32>,
pub clip_has_mask: bool,
pub inv: Matrix,
pub width: u32,
pub height: u32,
pub bpc: u8,
pub color_space: ImageColorSpace,
pub decode: Option<Arc<[[f32; 2]]>>,
pub samples: Arc<[u8]>,
pub sample_lut: Option<Arc<[[u8; 4]]>>,
pub smask: Option<Arc<ImageSMask>>,
pub mask: Option<ImageMask>,
pub interpolation: InterpolationMode,
pub footprint: [f64; 2],
pub is_stencil: bool,
pub stencil_rgb: [u8; 3],
pub alpha: u8,
pub blend: crate::page_ir::BlendMode,
}
impl PreparedImage {
fn components(&self) -> usize {
if self.is_stencil {
1
} else {
self.color_space.components()
}
}
fn row_bits(&self) -> usize {
let bits = self.width as usize * self.components() * self.bpc as usize;
bits.div_ceil(8) * 8
}
fn rgb8_len(&self) -> Option<usize> {
if self.is_stencil || !(1..=16).contains(&self.bpc) {
return None;
}
let source_bytes = self
.row_bits()
.checked_mul(self.height as usize)?
.checked_div(8)?;
if self.samples.len() < source_bytes {
return None;
}
(self.width as usize)
.checked_mul(self.height as usize)?
.checked_mul(3)
}
fn is_direct_rgb8(&self) -> bool {
self.bpc == 8
&& self.decode.is_none()
&& matches!(self.color_space, ImageColorSpace::Rgb)
&& self.rgb8_len().is_some()
}
fn source_pixel(&self, col: u32, row: u32) -> Option<[u8; 4]> {
self.pixel(col, row)
}
pub(crate) fn is_binary_box_filterable(&self) -> bool {
!self.is_stencil
&& self.bpc == 1
&& self.sample_lut.as_ref().is_some_and(|lut| lut.len() >= 2)
&& self.smask.is_none()
&& self.mask.is_none()
&& (self.footprint[0] > 1.0 || self.footprint[1] > 1.0)
&& self.inv.b.abs() < 1e-12
&& self.inv.c.abs() < 1e-12
}
pub(crate) fn lut_nearest_opaque(&self) -> Option<&[[u8; 4]]> {
if self.is_stencil || !matches!(self.bpc, 1 | 2 | 4) || self.components() != 1 {
return None;
}
let lut = self.sample_lut.as_ref()?;
if lut.len() != 1usize << self.bpc || lut.iter().any(|c| c[3] != 255) {
return None;
}
let needed = (self.row_bits() / 8).checked_mul(self.height as usize)?;
(self.samples.len() >= needed).then_some(&lut[..])
}
pub(crate) fn binary_box_lut(&self) -> Option<([u8; 4], [u8; 4])> {
let lut = self.sample_lut.as_ref()?;
let zero = lut.first().copied().unwrap_or([0, 0, 0, 255]);
let one = lut.get(1).copied().unwrap_or(zero);
Some((zero, one))
}
fn stencil_decode_inverted(&self) -> bool {
self.decode
.as_ref()
.map(|d| d.first().map(|p| p[0] > p[1]).unwrap_or(false))
.unwrap_or(false)
}
pub(crate) fn stencil_bilevel_lut(&self) -> Option<([u8; 4], [u8; 4])> {
if !self.is_stencil
|| self.bpc != 1
|| self.width == 0
|| self.height == 0
|| self.smask.is_some()
|| self.mask.is_some()
{
return None;
}
let needed = (self.row_bits() / 8).checked_mul(self.height as usize)?;
if self.samples.len() < needed {
return None;
}
let [r, g, b] = self.stencil_rgb;
let (paint, masked) = ([r, g, b, 255], [r, g, b, 0]);
Some(if self.stencil_decode_inverted() {
(masked, paint)
} else {
(paint, masked)
})
}
pub(crate) fn packed_row_bits(&self) -> usize {
self.row_bits()
}
pub(crate) fn minified_stencil_as_coverage(&self) -> Option<PreparedImage> {
if self.smask.is_some() {
return None;
}
let Some(ImageMask::Stencil(sm)) = self.mask.as_ref() else {
return None;
};
if sm.bits_per_component != 1 || sm.width == 0 || sm.height == 0 {
return None;
}
let row_bytes = (sm.width as usize).div_ceil(8);
if sm.samples.len() < row_bytes.checked_mul(sm.height as usize)? {
return None;
}
let footprint = self.smask_footprint(sm);
if !(footprint[0] > 1.0 || footprint[1] > 1.0) {
return None;
}
let inverted = sm
.decode
.as_ref()
.and_then(|d| d.first())
.is_some_and(|p| p[0] > p[1]);
let decode: [f32; 2] = if inverted { [0.0, 1.0] } else { [1.0, 0.0] };
Some(PreparedImage {
smask: Some(Arc::new(ImageSMask {
decode: Some(Arc::from([decode])),
..(**sm).clone()
})),
mask: None,
..self.clone()
})
}
pub(crate) fn gray8_promoted_to_rgb8(
&self,
rows: std::ops::Range<usize>,
) -> Option<PreparedImage> {
const MAX_PROMOTE_PIXELS: usize = 64 * 1024 * 1024;
if self.is_stencil
|| self.bpc != 8
|| self.decode.is_some()
|| self.sample_lut.is_some()
|| matches!(self.mask, Some(ImageMask::ColorKey(_)))
|| !matches!(self.color_space, ImageColorSpace::Gray)
{
return None;
}
let n = (self.width as usize).checked_mul(self.height as usize)?;
if n == 0 || n > MAX_PROMOTE_PIXELS || self.samples.len() < n {
return None;
}
let mut rgb = zeroed_arc(n * 3);
let width = self.width as usize;
let last = rows.end.min(self.height as usize);
let first = rows.start.min(last);
for (&g, dst) in self.samples[first * width..last * width]
.iter()
.zip(unique_arc_mut(&mut rgb)[first * width * 3..last * width * 3].chunks_exact_mut(3))
{
dst.copy_from_slice(&[g, g, g]);
}
Some(PreparedImage {
color_space: ImageColorSpace::Rgb,
samples: rgb,
..self.clone()
})
}
pub(crate) fn source_rows_for(&self, y0: usize, y1: usize) -> std::ops::Range<usize> {
let height = self.height as usize;
if height == 0 || y1 <= y0 {
return 0..0;
}
if self.inv.b != 0.0 || self.inv.c != 0.0 {
return 0..height;
}
let fy = |y: usize| {
let v = self.inv.d * (y as f64 + 0.5) + self.inv.f;
(1.0 - v) * self.height as f64 - 0.5
};
let (a, b) = (fy(y0), fy(y1 - 1));
let reach = self.footprint[1].abs().max(1.0) * 0.5 + 2.0;
let (lo, hi) = ((a.min(b) - reach).floor(), (a.max(b) + reach).ceil());
if !lo.is_finite() || !hi.is_finite() {
return 0..height;
}
let last = (height - 1) as f64;
lo.clamp(0.0, last) as usize..hi.clamp(0.0, last) as usize + 1
}
pub(crate) fn generic_promotion_eligible(&self) -> bool {
const MAX_PROMOTE_PIXELS: usize = 64 * 1024 * 1024;
if self.is_stencil
|| !matches!(self.bpc, 8 | 16)
|| self.sample_lut.is_some()
|| matches!(self.mask, Some(ImageMask::ColorKey(_)))
|| !(matches!(
self.color_space,
ImageColorSpace::IccRgb { .. }
| ImageColorSpace::IccCmyk { .. }
| ImageColorSpace::Lab { .. }
| ImageColorSpace::TintLut { .. }
| ImageColorSpace::TintLut2 { .. }
) || self.is_sixteen_bit_device_family())
{
return false;
}
let Some(n) = (self.width as usize).checked_mul(self.height as usize) else {
return false;
};
n > 0
&& n <= MAX_PROMOTE_PIXELS
&& self.samples.len() >= self.row_bits() / 8 * self.height as usize
}
pub(crate) fn is_sixteen_bit_device_family(&self) -> bool {
self.bpc == 16
&& matches!(
self.color_space,
ImageColorSpace::Gray | ImageColorSpace::Rgb | ImageColorSpace::Cmyk
)
}
#[cfg(test)]
pub(crate) fn generic_promoted_to_rgb8(&self) -> Option<PreparedImage> {
let samples = self.generic_source_as_rgb8()?;
Some(self.with_rgb8_samples(samples))
}
pub(crate) fn with_rgb8_samples(&self, samples: Arc<[u8]>) -> PreparedImage {
PreparedImage {
color_space: ImageColorSpace::Rgb,
bpc: 8,
decode: None,
sample_lut: None,
samples,
..self.clone()
}
}
pub(crate) fn generic_source_as_rgb8(&self) -> Option<Arc<[u8]>> {
if !self.generic_promotion_eligible() {
return None;
}
let (w, h) = (self.width as usize, self.height as usize);
let n = w * h;
let mut out = zeroed_arc(n * 3);
let dst = unique_arc_mut(&mut out);
if let ImageColorSpace::IccRgb { trc, matrix } = &self.color_space
&& self.bpc == 8
&& self.decode.is_none()
{
for (src, px) in self.samples[..n * 3]
.chunks_exact(3)
.zip(dst.chunks_exact_mut(3))
{
let rgb = crate::color::icc::to_srgb_with(
trc,
matrix,
[
src[0] as f32 / 255.0,
src[1] as f32 / 255.0,
src[2] as f32 / 255.0,
],
);
px[0] = to_u8(rgb[0]);
px[1] = to_u8(rgb[1]);
px[2] = to_u8(rgb[2]);
}
return Some(out);
}
for row in 0..h {
for col in 0..w {
let p = self.pixel(col as u32, row as u32)?;
let o = (row * w + col) * 3;
dst[o..o + 3].copy_from_slice(&p[..3]);
}
}
Some(out)
}
pub(crate) fn cmyk_source_as_rgb8(&self, rows: std::ops::Range<usize>) -> Option<Vec<u8>> {
const MAX_CONVERT_PIXELS: usize = 64 * 1024 * 1024;
if self.is_stencil || self.bpc != 8 || !matches!(self.color_space, ImageColorSpace::Cmyk) {
return None;
}
let luts = match self.decode.as_deref() {
None => None,
Some(d) if d.len() >= 4 => Some(std::array::from_fn::<[u8; 256], 4, _>(|c| {
let [lo, hi] = d[c];
std::array::from_fn(|b| {
crate::color::cmyk::cmyk_component_to_u8(lo + (b as f32 / 255.0) * (hi - lo))
})
})),
Some(_) => return None,
};
let n = (self.width as usize).checked_mul(self.height as usize)?;
if n == 0 || n > MAX_CONVERT_PIXELS || self.samples.len() < n * 4 {
return None;
}
let mut out = vec![0u8; n * 3];
let width = self.width as usize;
let last = rows.end.min(self.height as usize);
let first = rows.start.min(last);
for (cmyk, rgb) in self.samples[first * width * 4..last * width * 4]
.chunks_exact(4)
.zip(out[first * width * 3..last * width * 3].chunks_exact_mut(3))
{
let [c, m, y, k] = match &luts {
None => [cmyk[0], cmyk[1], cmyk[2], cmyk[3]],
Some(l) => [
l[0][cmyk[0] as usize],
l[1][cmyk[1] as usize],
l[2][cmyk[2] as usize],
l[3][cmyk[3] as usize],
],
};
rgb.copy_from_slice(&crate::color::cmyk::adobe_cmyk_to_srgb_u8(c, m, y, k));
}
Some(out)
}
#[inline]
fn indexed_palette_index(&self, raw: u32, hival: u32) -> usize {
if self.decode.is_some() {
let maxv = ((1u64 << self.bpc.min(16)) - 1).max(1) as f32;
let normalized = raw as f32 / maxv;
let decoded = match self.decode.as_ref().and_then(|d| d.first()) {
Some([lo, hi]) => lo + normalized * (hi - lo),
None => normalized,
};
decoded.round().clamp(0.0, hival as f32) as u32 as usize
} else {
raw.min(hival) as usize
}
}
pub(crate) fn indexed_promoted_to_rgb8(&self) -> Option<PreparedImage> {
let samples = self.indexed_source_as_rgb8()?;
Some(PreparedImage {
color_space: ImageColorSpace::Rgb,
bpc: 8,
decode: None,
sample_lut: None,
samples,
..self.clone()
})
}
pub(crate) fn indexed_promotion_eligible(&self) -> bool {
const MAX_EXPAND_PIXELS: usize = 64 * 1024 * 1024;
if !matches!(self.color_space, ImageColorSpace::Indexed { .. })
|| self.is_stencil
|| !matches!(self.bpc, 2 | 4 | 8)
|| matches!(self.mask, Some(ImageMask::ColorKey(_)))
{
return false;
}
let (w, h) = (self.width as usize, self.height as usize);
let Some(n) = w.checked_mul(h) else {
return false;
};
let Some(source_bits) = self.row_bits().checked_mul(h) else {
return false;
};
n > 0 && n <= MAX_EXPAND_PIXELS && self.samples.len() >= source_bits / 8
}
pub(crate) fn indexed_source_as_rgb8(&self) -> Option<Arc<[u8]>> {
if !self.indexed_promotion_eligible() {
return None;
}
let ImageColorSpace::Indexed {
base,
hival,
lookup,
} = &self.color_space
else {
return None;
};
let (w, h) = (self.width as usize, self.height as usize);
let n = w * h;
let row_bits = self.row_bits();
let entries = 1usize << self.bpc;
let palette: Vec<[u8; 3]> = (0..entries as u32)
.map(|raw| {
let rgb = indexed_rgb(
base,
*hival,
lookup,
self.indexed_palette_index(raw, *hival),
);
[to_u8(rgb[0]), to_u8(rgb[1]), to_u8(rgb[2])]
})
.collect();
let mut out_arc = zeroed_arc(n * 3);
let out = unique_arc_mut(&mut out_arc);
if self.bpc == 8 {
for (&raw, rgb) in self.samples[..n].iter().zip(out.chunks_exact_mut(3)) {
rgb.copy_from_slice(&palette[raw as usize]);
}
} else {
let bpc = self.bpc as usize;
let mask = (entries - 1) as u8;
let per_byte = 8 / bpc;
let row_bytes = row_bits / 8;
for (row, out_row) in out.chunks_exact_mut(w * 3).enumerate() {
let src_row = &self.samples[row * row_bytes..row * row_bytes + row_bytes];
for (col, rgb) in out_row.chunks_exact_mut(3).enumerate() {
let byte = src_row[col / per_byte];
let shift = 8 - bpc * (col % per_byte + 1);
let raw = (byte >> shift) & mask;
rgb.copy_from_slice(&palette[raw as usize]);
}
}
}
Some(out_arc)
}
#[cfg(test)]
pub(crate) fn binary_box_average(
&self,
cols: &AxisTaps,
rows: &AxisTaps,
) -> Option<([u8; 4], u64)> {
self.binary_box_average_with(self.binary_box_lut()?, cols, rows)
}
pub(crate) fn binary_box_average_with(
&self,
(zero, one): ([u8; 4], [u8; 4]),
cols: &AxisTaps,
rows: &AxisTaps,
) -> Option<([u8; 4], u64)> {
let weight = cols.total.checked_mul(rows.total)?;
if weight == 0 {
return None;
}
let row_bits = self.row_bits();
let mut ones_w = 0u64;
for source_y in rows.lo..=rows.hi {
let base = source_y as usize * row_bits;
let row_ones = self.weighted_row_ones(base, cols);
let wy = rows.weight_at(source_y);
ones_w += wy * row_ones;
}
let taps = (cols.hi - cols.lo + 1) as u64 * (rows.hi - rows.lo + 1) as u64;
Some((mix_bilevel(zero, one, ones_w, weight), taps))
}
fn weighted_row_ones(&self, base_bit: usize, cols: &AxisTaps) -> u64 {
weighted_row_ones_in(&self.samples, base_bit, cols)
}
pub fn shade(&self, dx: f64, dy: f64) -> Option<[u8; 4]> {
self.shade_with_taps(dx, dy).0
}
#[cfg(feature = "profiling")]
pub fn shade_profiled(&self, dx: f64, dy: f64) -> (Option<[u8; 4]>, u64) {
self.shade_with_taps(dx, dy)
}
pub(crate) fn shade_clamped(&self, dx: f64, dy: f64) -> Option<[u8; 4]> {
let p = self.inv.apply(Point { x: dx, y: dy });
let ux = p.x.clamp(0.0, 1.0 - 1e-9);
let uy = p.y.clamp(0.0, 1.0 - 1e-9);
self.shade_uv(ux, uy).0
}
pub(crate) fn edge_coverage(&self, dx: f64, dy: f64) -> Option<u16> {
let mu = 0.5 * (self.inv.a.abs() + self.inv.c.abs());
let mv = 0.5 * (self.inv.b.abs() + self.inv.d.abs());
let p = self.inv.apply(Point { x: dx, y: dy });
if p.x >= mu && p.x <= 1.0 - mu && p.y >= mv && p.y <= 1.0 - mv {
return None; }
let full = (self.inv.a * self.inv.d - self.inv.b * self.inv.c).abs();
if full <= 1e-18 {
return Some(0);
}
if self.inv.b == 0.0 && self.inv.c == 0.0 {
let inside = (0.0..1.0).contains(&p.x) && (0.0..1.0).contains(&p.y);
return Some(if inside { 255 } else { 0 });
}
let mut poly: [[f64; 2]; 8] = [[0.0; 2]; 8];
let mut n = 4usize;
for (i, (cx, cy)) in [(-0.5, -0.5), (0.5, -0.5), (0.5, 0.5), (-0.5, 0.5)]
.into_iter()
.enumerate()
{
poly[i] = [
p.x + cx * self.inv.a + cy * self.inv.c,
p.y + cx * self.inv.b + cy * self.inv.d,
];
}
let mut scratch: [[f64; 2]; 8] = [[0.0; 2]; 8];
for (axis, keep_ge, bound) in [
(0, true, 0.0),
(0, false, 1.0),
(1, true, 0.0),
(1, false, 1.0),
] {
let mut m = 0usize;
for i in 0..n {
let a = poly[i];
let b = poly[(i + 1) % n];
let da = if keep_ge {
a[axis] - bound
} else {
bound - a[axis]
};
let db = if keep_ge {
b[axis] - bound
} else {
bound - b[axis]
};
if da >= 0.0 {
scratch[m] = a;
m += 1;
}
if (da >= 0.0) != (db >= 0.0) {
let t = da / (da - db);
scratch[m] = [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])];
m += 1;
}
if m >= scratch.len() {
break; }
}
poly[..m].copy_from_slice(&scratch[..m]);
n = m;
if n == 0 {
return Some(0);
}
}
let mut area2 = 0.0f64;
for i in 0..n {
let a = poly[i];
let b = poly[(i + 1) % n];
area2 += a[0] * b[1] - b[0] * a[1];
}
let cov = (area2.abs() * 0.5 / full).clamp(0.0, 1.0);
Some((cov * 255.0 + 0.5) as u16)
}
fn shade_with_taps(&self, dx: f64, dy: f64) -> (Option<[u8; 4]>, u64) {
let p = self.inv.apply(Point { x: dx, y: dy });
if p.x < 0.0 || p.x >= 1.0 || p.y < 0.0 || p.y >= 1.0 {
return (None, 0);
}
self.shade_uv(p.x, p.y)
}
fn shade_uv(&self, px: f64, py: f64) -> (Option<[u8; 4]>, u64) {
let p = Point { x: px, y: py };
let fx = p.x * self.width as f64 - 0.5;
let fy = (1.0 - p.y) * self.height as f64 - 0.5;
let (rgba, taps) = if self.footprint[0] > 1.0 || self.footprint[1] > 1.0 {
let Some((rgba, taps)) = self.area_average(fx, fy) else {
return (None, 0);
};
(rgba, taps as u64)
} else {
match self.interpolation {
InterpolationMode::Nearest => {
let col = clampi(fx.round() as i64, self.width);
let row = clampi(fy.round() as i64, self.height);
let Some(rgba) = self.pixel(col, row) else {
return (None, 1);
};
(rgba, 1)
}
InterpolationMode::Bilinear => {
let Some(rgba) = self.bilinear(fx, fy) else {
return (None, 4);
};
(rgba, 4)
}
}
};
if let Some(mask) = &self.mask
&& self.mask_hides(mask, fx, fy, p.x, p.y)
{
return (None, taps);
}
let a = match &self.smask {
Some(sm) => {
let mask_footprint = self.smask_footprint(sm);
let sa = sample_smask(sm, p.x, p.y, mask_footprint);
(rgba[3] as f32 * sa) as u8
}
None => rgba[3],
};
if a == 0 {
return (None, taps);
}
(Some([rgba[0], rgba[1], rgba[2], a]), taps)
}
pub(crate) fn box_taps_x(&self, fx: f64) -> Option<AxisTaps> {
axis_box_taps(fx, (self.footprint[0] * 0.5).max(0.5), self.width)
}
pub(crate) fn box_taps_y(&self, fy: f64) -> Option<AxisTaps> {
axis_box_taps(fy, (self.footprint[1] * 0.5).max(0.5), self.height)
}
pub(crate) fn smask_footprint(&self, sm: &ImageSMask) -> [f64; 2] {
[
(self.inv.a.abs() + self.inv.c.abs()) * sm.width as f64,
(self.inv.b.abs() + self.inv.d.abs()) * sm.height as f64,
]
}
pub(crate) fn smask_box_taps(f: f64, half_footprint: f64, len: u32) -> Option<AxisTaps> {
axis_box_taps(f, (half_footprint * 0.5).max(0.5), len)
}
fn area_average(&self, fx: f64, fy: f64) -> Option<([u8; 4], u32)> {
if !self.has_axis_aligned_footprint() {
return self.parallelogram_average(fx, fy);
}
let tx = self.box_taps_x(fx)?;
let ty = self.box_taps_y(fy)?;
let weight = tx.total.checked_mul(ty.total)?;
if weight == 0 {
return None;
}
let taps = (tx.hi - tx.lo + 1) * (ty.hi - ty.lo + 1);
let mut acc = [0u64; 4];
if !self.is_stencil
&& self.bpc == 8
&& self.decode.is_none()
&& matches!(self.color_space, ImageColorSpace::Rgb)
&& self.samples.len() >= self.width as usize * self.height as usize * 3
{
let stride = self.width as usize * 3;
for row in ty.lo..=ty.hi {
let wy = ty.weight_at(row);
let start = row as usize * stride + tx.lo as usize * 3;
let end = row as usize * stride + (tx.hi as usize + 1) * 3;
let src = self.samples.get(start..end)?;
for (col, rgb) in (tx.lo..).zip(src.chunks_exact(3)) {
let w = wy * tx.weight_at(col);
acc[0] += w * rgb[0] as u64;
acc[1] += w * rgb[1] as u64;
acc[2] += w * rgb[2] as u64;
acc[3] += w * 255;
}
}
return weighted_average_rgba(acc, weight).map(|rgba| (rgba, taps));
}
if let Some(lut) = &self.sample_lut {
let row_bits = self.row_bits();
if self.bpc == 1 {
let zero = lut.first().copied().unwrap_or([0, 0, 0, 255]);
let one = lut.get(1).copied().unwrap_or(zero);
let mut ones_w = 0u64;
for row in ty.lo..=ty.hi {
let base = row as usize * row_bits;
ones_w += ty.weight_at(row) * self.weighted_row_ones(base, &tx);
}
return Some((mix_bilevel(zero, one, ones_w, weight), taps));
}
for row in ty.lo..=ty.hi {
let wy = ty.weight_at(row);
for col in tx.lo..=tx.hi {
let w = wy * tx.weight_at(col);
let bit = row as usize * row_bits + col as usize * self.bpc as usize;
let raw = read_bits(&self.samples, bit, self.bpc as usize) as usize;
let p = lut.get(raw).copied().unwrap_or([0, 0, 0, 255]);
for c in 0..4 {
acc[c] += w * p[c] as u64;
}
}
}
return weighted_average_rgba(acc, weight).map(|rgba| (rgba, taps));
}
for row in ty.lo..=ty.hi {
let wy = ty.weight_at(row);
for col in tx.lo..=tx.hi {
if let Some(p) = self.pixel(col, row) {
let w = wy * tx.weight_at(col);
for c in 0..4 {
acc[c] += w * p[c] as u64;
}
}
}
}
let out = weighted_average_rgba(acc, weight)?;
if self.is_stencil {
return Some((
[
self.stencil_rgb[0],
self.stencil_rgb[1],
self.stencil_rgb[2],
out[3],
],
taps,
));
}
Some((out, taps))
}
fn source_footprint_basis(&self) -> ([f64; 2], [f64; 2]) {
(
[
self.inv.a * self.width as f64,
-self.inv.b * self.height as f64,
],
[
self.inv.c * self.width as f64,
-self.inv.d * self.height as f64,
],
)
}
fn has_axis_aligned_footprint(&self) -> bool {
let (dx, dy) = self.source_footprint_basis();
const EPS: f64 = 1e-9;
(dx[1].abs() <= EPS && dy[0].abs() <= EPS) || (dx[0].abs() <= EPS && dy[1].abs() <= EPS)
}
fn parallelogram_average(&self, fx: f64, fy: f64) -> Option<([u8; 4], u32)> {
const WEIGHT_SCALE: f64 = 1_048_576.0;
let (dx, dy) = self.source_footprint_basis();
let hx = [dx[0] * 0.5, dx[1] * 0.5];
let hy = [dy[0] * 0.5, dy[1] * 0.5];
let footprint = ConvexQuad::new([
[fx - hx[0] - hy[0], fy - hx[1] - hy[1]],
[fx + hx[0] - hy[0], fy + hx[1] - hy[1]],
[fx + hx[0] + hy[0], fy + hx[1] + hy[1]],
[fx - hx[0] + hy[0], fy - hx[1] + hy[1]],
])?;
let lo_x = clampi((footprint.bounds[0] + 0.5).floor() as i64, self.width);
let hi_x = clampi((footprint.bounds[2] + 0.5).floor() as i64, self.width).max(lo_x);
let lo_y = clampi((footprint.bounds[1] + 0.5).floor() as i64, self.height);
let hi_y = clampi((footprint.bounds[3] + 0.5).floor() as i64, self.height).max(lo_y);
let direct_rgb = !self.is_stencil
&& self.bpc == 8
&& self.decode.is_none()
&& matches!(self.color_space, ImageColorSpace::Rgb)
&& self.samples.len() >= self.width as usize * self.height as usize * 3;
let mut acc = [0u64; 4];
let mut total_weight = 0u64;
let mut taps = 0u32;
for row in lo_y..=hi_y {
for col in lo_x..=hi_x {
let area = footprint.rect_overlap_area(
col as f64 - 0.5,
col as f64 + 0.5,
row as f64 - 0.5,
row as f64 + 0.5,
);
if area <= f64::EPSILON {
continue;
}
let weight = ((area * WEIGHT_SCALE).round() as u64).max(1);
total_weight = total_weight.checked_add(weight)?;
taps = taps.saturating_add(1);
let pixel = if direct_rgb {
let offset =
(row as usize * self.width as usize + col as usize).checked_mul(3)?;
let rgb = self.samples.get(offset..offset + 3)?;
Some([rgb[0], rgb[1], rgb[2], 255])
} else {
self.pixel(col, row)
};
if let Some(pixel) = pixel {
for channel in 0..4 {
acc[channel] += weight * pixel[channel] as u64;
}
}
}
}
let mut out = weighted_average_rgba(acc, total_weight)?;
if self.is_stencil {
out[..3].copy_from_slice(&self.stencil_rgb);
}
Some((out, taps))
}
fn bilinear(&self, fx: f64, fy: f64) -> Option<[u8; 4]> {
let x0 = fx.floor();
let y0 = fy.floor();
let tx = (fx - x0) as f32;
let ty = (fy - y0) as f32;
let c = |ix: i64, iy: i64| self.pixel(clampi(ix, self.width), clampi(iy, self.height));
let p00 = c(x0 as i64, y0 as i64)?;
let p10 = c(x0 as i64 + 1, y0 as i64)?;
let p01 = c(x0 as i64, y0 as i64 + 1)?;
let p11 = c(x0 as i64 + 1, y0 as i64 + 1)?;
let mut out = [0u8; 4];
for ch in 0..4 {
let top = p00[ch] as f32 * (1.0 - tx) + p10[ch] as f32 * tx;
let bot = p01[ch] as f32 * (1.0 - tx) + p11[ch] as f32 * tx;
out[ch] = (top * (1.0 - ty) + bot * ty).clamp(0.0, 255.0) as u8;
}
if p00[3] == p10[3] && p00[3] == p01[3] && p00[3] == p11[3] {
out[3] = p00[3];
}
Some(out)
}
fn pixel(&self, col: u32, row: u32) -> Option<[u8; 4]> {
let ncomp = self.components();
let row_bits = self.row_bits();
let maxv = ((1u64 << self.bpc.min(16)) - 1).max(1) as f32;
let read = |c: usize| -> u32 {
let bit = row as usize * row_bits + (col as usize * ncomp + c) * self.bpc as usize;
read_bits(&self.samples, bit, self.bpc as usize)
};
if self.is_stencil {
let mut v = read(0);
if self.stencil_decode_inverted() {
v = 1 - v;
}
if v == 0 {
return Some([
self.stencil_rgb[0],
self.stencil_rgb[1],
self.stencil_rgb[2],
255,
]);
}
return None;
}
if let Some(lut) = &self.sample_lut {
return lut.get(read(0) as usize).copied();
}
if self.bpc == 8
&& self.decode.is_none()
&& self.samples.len() >= self.width as usize * self.height as usize * self.components()
{
let pixel = row as usize * self.width as usize + col as usize;
match self.color_space {
ImageColorSpace::Rgb => {
let offset = pixel * 3;
let rgb = self.samples.get(offset..offset + 3)?;
return Some([rgb[0], rgb[1], rgb[2], 255]);
}
ImageColorSpace::Gray => {
let g = *self.samples.get(pixel)?;
return Some([g, g, g, 255]);
}
_ => {}
}
}
let comp = |c: usize| -> f32 {
let raw = read(c) as f32 / maxv;
match self.decode.as_ref().and_then(|d| d.get(c)) {
Some([lo, hi]) => lo + raw * (hi - lo),
None => raw,
}
};
let rgb = match &self.color_space {
ImageColorSpace::Gray => {
let g = comp(0).clamp(0.0, 1.0);
[g, g, g]
}
ImageColorSpace::Rgb => [
comp(0).clamp(0.0, 1.0),
comp(1).clamp(0.0, 1.0),
comp(2).clamp(0.0, 1.0),
],
ImageColorSpace::Cmyk => crate::color::cmyk_to_rgb(
comp(0).clamp(0.0, 1.0),
comp(1).clamp(0.0, 1.0),
comp(2).clamp(0.0, 1.0),
comp(3).clamp(0.0, 1.0),
),
ImageColorSpace::Lab { white_point, range } => {
let axis = |v: f32, lo: f32, hi: f32| lo + v.clamp(0.0, 1.0) * (hi - lo);
crate::color::lab_to_rgb(
axis(comp(0), 0.0, 100.0),
axis(comp(1), range[0], range[1]),
axis(comp(2), range[2], range[3]),
*white_point,
*range,
)
}
ImageColorSpace::Indexed {
base,
hival,
lookup,
} => {
let idx = self.indexed_palette_index(read(0), *hival);
indexed_rgb(base, *hival, lookup, idx)
}
ImageColorSpace::TintLut { rgb } => tint_lut_rgb(rgb, comp(0)),
ImageColorSpace::TintLut2 { rgb } => tint_lut2_rgb(rgb, comp(0), comp(1)),
ImageColorSpace::IccRgb { trc, matrix } => {
crate::color::icc::to_srgb_with(trc, matrix, [comp(0), comp(1), comp(2)])
}
ImageColorSpace::IccCmyk { transform } => crate::color::icc::cmyk_to_srgb_with(
transform.grid as usize,
[
&transform.input_tables[0],
&transform.input_tables[1],
&transform.input_tables[2],
&transform.input_tables[3],
],
&transform.clut,
[
&transform.output_tables[0],
&transform.output_tables[1],
&transform.output_tables[2],
],
[comp(0), comp(1), comp(2), comp(3)],
),
};
Some([to_u8(rgb[0]), to_u8(rgb[1]), to_u8(rgb[2]), 255])
}
fn mask_hides(&self, mask: &ImageMask, fx: f64, fy: f64, u: f64, v: f64) -> bool {
match mask {
ImageMask::ColorKey(ranges) => {
let col = clampi(fx.round() as i64, self.width);
let row = clampi(fy.round() as i64, self.height);
self.color_key_hit(ranges, col, row)
}
ImageMask::Stencil(sm) => stencil_hides(sm, u, v),
}
}
fn color_key_hit(&self, ranges: &[[u32; 2]], col: u32, row: u32) -> bool {
let ncomp = self.components();
if ranges.len() != ncomp {
return false;
}
let row_bits = self.row_bits();
for (c, &[lo, hi]) in ranges.iter().enumerate() {
let bit = row as usize * row_bits + (col as usize * ncomp + c) * self.bpc as usize;
let raw = read_bits(&self.samples, bit, self.bpc as usize);
if raw < lo || raw > hi {
return false;
}
}
true
}
}
struct ConvexQuad {
vertices: [[f64; 2]; 4],
edges: [[f64; 3]; 4],
bounds: [f64; 4],
area: f64,
}
impl ConvexQuad {
fn new(vertices: [[f64; 2]; 4]) -> Option<Self> {
let mut twice_area = 0.0;
for index in 0..4 {
let a = vertices[index];
let b = vertices[(index + 1) % 4];
twice_area += a[0] * b[1] - b[0] * a[1];
}
if !twice_area.is_finite() || twice_area.abs() <= f64::EPSILON {
return None;
}
let orientation = twice_area.signum();
let mut edges = [[0.0; 3]; 4];
for index in 0..4 {
let a = vertices[index];
let b = vertices[(index + 1) % 4];
let ex = b[0] - a[0];
let ey = b[1] - a[1];
edges[index] = [
-orientation * ey,
orientation * ex,
orientation * (ey * a[0] - ex * a[1]),
];
}
let min_x = vertices.iter().map(|p| p[0]).fold(f64::INFINITY, f64::min);
let max_x = vertices
.iter()
.map(|p| p[0])
.fold(f64::NEG_INFINITY, f64::max);
let min_y = vertices.iter().map(|p| p[1]).fold(f64::INFINITY, f64::min);
let max_y = vertices
.iter()
.map(|p| p[1])
.fold(f64::NEG_INFINITY, f64::max);
Some(Self {
vertices,
edges,
bounds: [min_x, min_y, max_x, max_y],
area: twice_area.abs() * 0.5,
})
}
fn rect_overlap_area(&self, x0: f64, x1: f64, y0: f64, y1: f64) -> f64 {
if x1 <= self.bounds[0]
|| x0 >= self.bounds[2]
|| y1 <= self.bounds[1]
|| y0 >= self.bounds[3]
{
return 0.0;
}
let corners = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]];
let mut rect_inside = true;
for &[a, b, c] in &self.edges {
let mut inside = 0u8;
for point in corners {
inside += (a * point[0] + b * point[1] + c >= -1e-12) as u8;
}
if inside == 0 {
return 0.0;
}
rect_inside &= inside == 4;
}
if rect_inside {
return 1.0;
}
if self.vertices.iter().all(|p| {
p[0] >= x0 - 1e-12 && p[0] <= x1 + 1e-12 && p[1] >= y0 - 1e-12 && p[1] <= y1 + 1e-12
}) {
return self.area.clamp(0.0, 1.0);
}
polygon_rect_overlap_area_clipped(&self.vertices, x0, x1, y0, y1)
}
}
fn polygon_rect_overlap_area_clipped(
quad: &[[f64; 2]; 4],
x0: f64,
x1: f64,
y0: f64,
y1: f64,
) -> f64 {
let mut polygon = [[0.0; 2]; 12];
polygon[..4].copy_from_slice(quad);
let mut count = 4usize;
let mut scratch = [[0.0; 2]; 12];
for (axis, keep_greater, bound) in [
(0usize, true, x0),
(0usize, false, x1),
(1usize, true, y0),
(1usize, false, y1),
] {
let mut next_count = 0usize;
for index in 0..count {
let a = polygon[index];
let b = polygon[(index + 1) % count];
let da = if keep_greater {
a[axis] - bound
} else {
bound - a[axis]
};
let db = if keep_greater {
b[axis] - bound
} else {
bound - b[axis]
};
if da >= 0.0 {
scratch[next_count] = a;
next_count += 1;
}
if (da >= 0.0) != (db >= 0.0) {
let t = da / (da - db);
scratch[next_count] = [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])];
next_count += 1;
}
}
if next_count == 0 {
return 0.0;
}
polygon[..next_count].copy_from_slice(&scratch[..next_count]);
count = next_count;
}
let mut twice_area = 0.0;
for index in 0..count {
let a = polygon[index];
let b = polygon[(index + 1) % count];
twice_area += a[0] * b[1] - b[0] * a[1];
}
(twice_area.abs() * 0.5).clamp(0.0, 1.0)
}
pub(crate) fn build_sample_lut(
bits_per_component: u8,
color_space: &ImageColorSpace,
decode: Option<&[[f32; 2]]>,
is_stencil: bool,
) -> Option<Arc<[[u8; 4]]>> {
if is_stencil || bits_per_component == 0 || bits_per_component > 4 {
return None;
}
if color_space.components() != 1 {
return None;
}
let entries = 1usize << bits_per_component;
let maxv = (entries - 1).max(1) as f32;
let mut lut = Vec::with_capacity(entries);
for raw in 0..entries {
let normalized = raw as f32 / maxv;
let decoded = match decode.and_then(|d| d.first()) {
Some([lo, hi]) => lo + normalized * (hi - lo),
None => normalized,
};
let rgb = match color_space {
ImageColorSpace::Gray => {
let g = decoded.clamp(0.0, 1.0);
[g, g, g]
}
ImageColorSpace::Indexed {
base,
hival,
lookup,
} => {
let idx = if decode.is_some() {
decoded.round().clamp(0.0, *hival as f32) as usize
} else {
raw.min(*hival as usize)
};
indexed_rgb(base, *hival, lookup, idx)
}
ImageColorSpace::TintLut { rgb } => tint_lut_rgb(rgb, decoded),
ImageColorSpace::Rgb
| ImageColorSpace::Cmyk
| ImageColorSpace::Lab { .. }
| ImageColorSpace::TintLut2 { .. }
| ImageColorSpace::IccRgb { .. }
| ImageColorSpace::IccCmyk { .. } => {
return None;
}
};
lut.push([to_u8(rgb[0]), to_u8(rgb[1]), to_u8(rgb[2]), 255]);
}
Some(lut.into())
}
pub(crate) const AXIS_TAP_SCALE: u64 = 4096;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct AxisTaps {
pub lo: u32,
pub hi: u32,
pub w_lo: u64,
pub w_hi: u64,
pub total: u64,
}
impl AxisTaps {
#[inline]
pub(crate) fn weight_at(&self, i: u32) -> u64 {
if i == self.lo {
self.w_lo
} else if i == self.hi {
self.w_hi
} else {
AXIS_TAP_SCALE
}
}
}
pub(crate) fn axis_box_taps(f: f64, half: f64, len: u32) -> Option<AxisTaps> {
if len == 0 || !f.is_finite() {
return None;
}
let left = (f + 0.5 - half).max(0.0);
let right = (f + 0.5 + half).min(len as f64);
if right <= left {
let nearest = clampi(f.round() as i64, len);
return Some(AxisTaps {
lo: nearest,
hi: nearest,
w_lo: AXIS_TAP_SCALE,
w_hi: AXIS_TAP_SCALE,
total: AXIS_TAP_SCALE,
});
}
let lo = clampi(left.floor() as i64, len);
let hi = clampi((right.ceil() - 1.0) as i64, len).max(lo);
let scale = AXIS_TAP_SCALE as f64;
if lo == hi {
let w = (((right - left).min(1.0) * scale).round() as u64).max(1);
return Some(AxisTaps {
lo,
hi,
w_lo: w,
w_hi: w,
total: w,
});
}
let w_lo = ((((lo + 1) as f64 - left).clamp(0.0, 1.0) * scale).round() as u64).max(1);
let w_hi = (((right - hi as f64).clamp(0.0, 1.0) * scale).round() as u64).max(1);
let interior = (hi - lo).saturating_sub(1) as u64;
Some(AxisTaps {
lo,
hi,
w_lo,
w_hi,
total: w_lo + w_hi + interior * AXIS_TAP_SCALE,
})
}
#[inline]
pub(crate) fn mix_bilevel(zero: [u8; 4], one: [u8; 4], ones_w: u64, weight: u64) -> [u8; 4] {
if ones_w == 0 {
return zero;
}
if ones_w >= weight {
return one;
}
let zeros_w = weight - ones_w;
let mut out = [0u8; 4];
for c in 0..4 {
let acc = zero[c] as u64 * zeros_w + one[c] as u64 * ones_w;
out[c] = ((acc + weight / 2) / weight) as u8;
}
out
}
#[inline]
fn weighted_average_rgba(acc: [u64; 4], weight: u64) -> Option<[u8; 4]> {
(weight != 0).then(|| {
[
((acc[0] + weight / 2) / weight).min(255) as u8,
((acc[1] + weight / 2) / weight).min(255) as u8,
((acc[2] + weight / 2) / weight).min(255) as u8,
((acc[3] + weight / 2) / weight).min(255) as u8,
]
})
}
fn stencil_hides(sm: &ImageSMask, u: f64, v: f64) -> bool {
if sm.width == 0 || sm.height == 0 {
return false;
}
stencil_hides_at(sm, stencil_col(sm, u), stencil_row(sm, v))
}
pub(crate) fn stencil_col(sm: &ImageSMask, u: f64) -> u32 {
clampi((u * sm.width as f64) as i64, sm.width)
}
pub(crate) fn stencil_row(sm: &ImageSMask, v: f64) -> u32 {
clampi(((1.0 - v) * sm.height as f64) as i64, sm.height)
}
pub(crate) fn stencil_hides_at(sm: &ImageSMask, col: u32, row: u32) -> bool {
let (col, row) = (col as usize, row as usize);
let bpc = sm.bits_per_component.max(1) as usize;
let row_bits = (sm.width as usize * bpc).div_ceil(8) * 8;
let bit = row * row_bits + col * bpc;
let raw = read_bits(&sm.samples, bit, bpc);
let inverted = sm
.decode
.as_ref()
.and_then(|d| d.first())
.map(|p| p[0] > p[1])
.unwrap_or(false);
if inverted { raw == 0 } else { raw != 0 }
}
fn indexed_rgb(base: &ImageColorSpace, _hival: u32, lookup: &[u8], idx: usize) -> [f32; 3] {
let bn = base.components();
let off = idx * bn;
let get = |c: usize| {
lookup
.get(off + c)
.map(|b| *b as f32 / 255.0)
.unwrap_or(0.0)
};
match base {
ImageColorSpace::Gray => {
let g = get(0);
[g, g, g]
}
ImageColorSpace::Rgb => [get(0), get(1), get(2)],
ImageColorSpace::Cmyk => crate::color::cmyk_to_rgb(get(0), get(1), get(2), get(3)),
ImageColorSpace::Lab { white_point, range } => {
let axis = |v: f32, lo: f32, hi: f32| lo + v * (hi - lo);
crate::color::lab_to_rgb(
axis(get(0), 0.0, 100.0),
axis(get(1), range[0], range[1]),
axis(get(2), range[2], range[3]),
*white_point,
*range,
)
}
ImageColorSpace::Indexed { .. } => {
let g = get(0);
[g, g, g]
}
ImageColorSpace::TintLut { rgb } => tint_lut_rgb(rgb, get(0)),
ImageColorSpace::TintLut2 { rgb } => tint_lut2_rgb(rgb, get(0), get(1)),
ImageColorSpace::IccRgb { trc, matrix } => {
crate::color::icc::to_srgb_with(trc, matrix, [get(0), get(1), get(2)])
}
ImageColorSpace::IccCmyk { transform } => crate::color::icc::cmyk_to_srgb_with(
transform.grid as usize,
[
&transform.input_tables[0],
&transform.input_tables[1],
&transform.input_tables[2],
&transform.input_tables[3],
],
&transform.clut,
[
&transform.output_tables[0],
&transform.output_tables[1],
&transform.output_tables[2],
],
[get(0), get(1), get(2), get(3)],
),
}
}
fn tint_lut2_rgb(rgb: &[u8], a: f32, b: f32) -> [f32; 3] {
let ia = ((a.clamp(0.0, 1.0) * 255.0).round() as usize).min(255);
let ib = ((b.clamp(0.0, 1.0) * 255.0).round() as usize).min(255);
let o = (ia * 256 + ib) * 3;
match rgb.get(o..o + 3) {
Some(p) => [
p[0] as f32 / 255.0,
p[1] as f32 / 255.0,
p[2] as f32 / 255.0,
],
None => [0.0, 0.0, 0.0],
}
}
fn tint_lut_rgb(rgb: &[u8], tint: f32) -> [f32; 3] {
let idx = ((tint.clamp(0.0, 1.0) * 255.0).round() as usize).min(255);
let o = idx * 3;
match rgb.get(o..o + 3) {
Some(p) => [
p[0] as f32 / 255.0,
p[1] as f32 / 255.0,
p[2] as f32 / 255.0,
],
None => [0.0, 0.0, 0.0],
}
}
pub(crate) fn smask_row_bits(sm: &ImageSMask) -> usize {
(sm.width as usize * sm.bits_per_component as usize).div_ceil(8) * 8
}
pub(crate) fn bilevel_smask_coverage(sm: &ImageSMask, tx: &AxisTaps, ty: &AxisTaps) -> f32 {
let row_bits = smask_row_bits(sm);
let weight = tx.total.saturating_mul(ty.total).max(1);
let mut ones_w = 0u64;
for row in ty.lo..=ty.hi {
let row_ones = weighted_row_ones_in(&sm.samples, row as usize * row_bits, tx);
ones_w = ones_w.saturating_add(ty.weight_at(row).saturating_mul(row_ones));
}
ones_w as f32 / weight as f32
}
pub(crate) fn gray8_smask_coverage(sm: &ImageSMask, tx: &AxisTaps, ty: &AxisTaps) -> f32 {
let row_bytes = smask_row_bits(sm) / 8;
let weight = tx.total.saturating_mul(ty.total).max(1);
let maxv = 255.0f64;
let mut acc = 0.0f64;
for row in ty.lo..=ty.hi {
let wy = ty.weight_at(row) as f64;
let base = row as usize * row_bytes;
let texels = &sm.samples[base + tx.lo as usize..=base + tx.hi as usize];
for (col, &texel) in (tx.lo..).zip(texels) {
let sample = texel as f64 / maxv;
acc += wy * tx.weight_at(col) as f64 * sample;
}
}
(acc / weight as f64) as f32
}
pub(crate) fn apply_smask_decode(sm: &ImageSMask, raw: f32) -> f32 {
match sm.decode.as_ref().and_then(|d| d.first()) {
Some([lo, hi]) => (lo + raw * (hi - lo)).clamp(0.0, 1.0),
None => raw,
}
}
fn sample_smask(sm: &ImageSMask, u: f64, v: f64, footprint: [f64; 2]) -> f32 {
if sm.width == 0 || sm.height == 0 {
return 1.0;
}
let row_bits = smask_row_bits(sm);
let maxv = ((1u64 << sm.bits_per_component.min(16)) - 1).max(1) as f32;
let fx = u * sm.width as f64 - 0.5;
let fy = (1.0 - v) * sm.height as f64 - 0.5;
let raw = if footprint[0] > 1.0 || footprint[1] > 1.0 {
let Some(tx) = PreparedImage::smask_box_taps(fx, footprint[0], sm.width) else {
return 1.0;
};
let Some(ty) = PreparedImage::smask_box_taps(fy, footprint[1], sm.height) else {
return 1.0;
};
let weight = tx.total.saturating_mul(ty.total).max(1);
if sm.bits_per_component == 1 {
bilevel_smask_coverage(sm, &tx, &ty)
} else {
let bpc = sm.bits_per_component as usize;
let mut acc = 0.0f64;
for row in ty.lo..=ty.hi {
let wy = ty.weight_at(row) as f64;
for col in tx.lo..=tx.hi {
let bit = row as usize * row_bits + col as usize * bpc;
let sample = read_bits(&sm.samples, bit, bpc) as f64 / maxv as f64;
acc += wy * tx.weight_at(col) as f64 * sample;
}
}
(acc / weight as f64) as f32
}
} else {
let col = clampi((u * sm.width as f64) as i64, sm.width) as usize;
let row = clampi(((1.0 - v) * sm.height as f64) as i64, sm.height) as usize;
let bit = row * row_bits + col * sm.bits_per_component as usize;
read_bits(&sm.samples, bit, sm.bits_per_component as usize) as f32 / maxv
};
apply_smask_decode(sm, raw)
}
fn read_bits(data: &[u8], bit: usize, bits: usize) -> u32 {
if bit.is_multiple_of(8) {
match bits {
8 => return data.get(bit / 8).copied().unwrap_or(0) as u32,
16 => {
let i = bit / 8;
let hi = data.get(i).copied().unwrap_or(0) as u32;
let lo = data.get(i + 1).copied().unwrap_or(0) as u32;
return (hi << 8) | lo;
}
_ => {}
}
}
let mut v: u32 = 0;
for i in 0..bits {
let b = bit + i;
let byte = b / 8;
let shift = 7 - (b % 8);
let bitval = data.get(byte).map(|x| (x >> shift) & 1).unwrap_or(0);
v = (v << 1) | bitval as u32;
}
v
}
fn count_one_bits(data: &[u8], start_bit: usize, bit_len: usize) -> u32 {
if bit_len == 0 {
return 0;
}
let mut bit = start_bit;
let end = start_bit.saturating_add(bit_len);
let mut count = 0u32;
if !bit.is_multiple_of(8) {
let take = (8 - bit % 8).min(end - bit);
let offset = bit % 8;
let mask = (0xffu8 >> offset) & (0xffu8 << (8 - offset - take));
count += (data.get(bit / 8).copied().unwrap_or(0) & mask).count_ones();
bit += take;
}
while bit + 8 <= end {
count += data.get(bit / 8).copied().unwrap_or(0).count_ones();
bit += 8;
}
if bit < end {
let take = end - bit;
let mask = 0xffu8 << (8 - take);
count += (data.get(bit / 8).copied().unwrap_or(0) & mask).count_ones();
}
count
}
pub(crate) fn weighted_row_ones_in(data: &[u8], base_bit: usize, cols: &AxisTaps) -> u64 {
let bit_at = |x: u32| -> u64 {
let b = base_bit + x as usize;
let byte = data.get(b / 8).copied().unwrap_or(0);
((byte >> (7 - (b % 8))) & 1) as u64
};
if cols.lo == cols.hi {
return cols.w_lo * bit_at(cols.lo);
}
let mut ones = cols.w_lo * bit_at(cols.lo) + cols.w_hi * bit_at(cols.hi);
if cols.hi - cols.lo >= 2 {
let interior = count_one_bits(
data,
base_bit + cols.lo as usize + 1,
(cols.hi - cols.lo - 1) as usize,
) as u64;
ones += AXIS_TAP_SCALE * interior;
}
ones
}
#[inline]
fn clampi(v: i64, len: u32) -> u32 {
v.clamp(0, (len as i64 - 1).max(0)) as u32
}
#[inline]
fn to_u8(v: f32) -> u8 {
(v * 255.0 + 0.5).clamp(0.0, 255.0) as u8
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use crate::page_ir::{BlendMode, DeviceRect};
fn img(
width: u32,
height: u32,
color_space: ImageColorSpace,
samples: Vec<u8>,
mask: Option<ImageMask>,
) -> PreparedImage {
let sample_lut = build_sample_lut(8, &color_space, None, false);
PreparedImage {
origin: crate::page_ir::PaintOrigin::PageContent,
bounds: DeviceRect {
x: 0,
y: 0,
width,
height,
},
clip: None,
clip_has_mask: false,
inv: Matrix::IDENTITY,
width,
height,
bpc: 8,
color_space,
decode: None,
samples: Arc::from(samples),
sample_lut,
smask: None,
mask,
interpolation: InterpolationMode::Nearest,
footprint: [1.0, 1.0],
is_stencil: false,
stencil_rgb: [0, 0, 0],
alpha: 255,
blend: BlendMode::Normal,
}
}
fn stencil(width: u32, height: u32, samples: Vec<u8>, decode: Option<[f32; 2]>) -> ImageMask {
ImageMask::Stencil(Arc::new(ImageSMask {
width,
height,
bits_per_component: 1,
decode: decode.map(|d| Arc::from(vec![d])),
samples: Arc::from(samples),
codec: None,
codec_data: None,
codec_parms: None,
}))
}
#[test]
fn cmyk_rgb8_conversion_matches_pixel_with_and_without_decode() {
let (w, h) = (64u32, 64u32);
let mut samples = Vec::new();
let mut x = 0x2545_F491_4F6C_DD1Du64;
for i in 0..(w * h) {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
let r = x.to_le_bytes();
let v = (i % 256) as u8;
let px = match i / 256 % 4 {
0 => [v, r[1], r[2], r[3]],
1 => [r[0], v, r[2], r[3]],
2 => [r[0], r[1], v, r[3]],
_ => [r[0], r[1], r[2], v],
};
samples.extend_from_slice(&px);
}
let decodes: [Option<Vec<[f32; 2]>>; 4] = [
None,
Some(vec![[1.0, 0.0]; 4]),
Some(vec![[0.1, 0.9], [0.0, 2.0], [-1.0, 1.0], [0.5, 0.5]]),
Some(vec![[0.0, 1.0]; 4]),
];
for decode in decodes {
let mut image = img(w, h, ImageColorSpace::Cmyk, samples.clone(), None);
image.decode = decode.map(Arc::from);
let rgb = image
.cmyk_source_as_rgb8(0..h as usize)
.expect("convertible");
for row in 0..h {
for col in 0..w {
let want = image.pixel(col, row).unwrap();
let o = (row * w + col) as usize * 3;
assert_eq!(
&rgb[o..o + 3],
&want[..3],
"({col},{row}) decode {:?}",
image.decode
);
}
}
}
}
#[test]
fn sixteen_bit_device_images_promote_exactly() {
let (w, h) = (24u32, 20u32);
let mut x = 0x1234_5678_9ABC_DEF1u64;
let mut next = move || {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x
};
for (space, comps) in [
(ImageColorSpace::Gray, 1usize),
(ImageColorSpace::Rgb, 3),
(ImageColorSpace::Cmyk, 4),
] {
let mut samples = Vec::new();
for _ in 0..(w * h) as usize * comps {
let v = (next() >> 16) as u16;
samples.extend_from_slice(&v.to_be_bytes());
}
samples[..2].copy_from_slice(&0u16.to_be_bytes());
samples[2..4].copy_from_slice(&u16::MAX.to_be_bytes());
let decodes: [Option<Vec<[f32; 2]>>; 3] = [
None,
Some(vec![[1.0, 0.0]; comps]),
Some(vec![[0.2, 0.7]; comps]),
];
for decode in decodes {
let mut image = img(w, h, space.clone(), samples.clone(), None);
image.bpc = 16;
image.sample_lut = None;
image.decode = decode.map(Arc::from);
assert!(image.generic_promotion_eligible(), "{space:?}");
let promoted = image.generic_promoted_to_rgb8().expect("promotes");
assert_eq!(promoted.bpc, 8);
for row in 0..h {
for col in 0..w {
let want = image.pixel(col, row).unwrap();
let got = promoted.pixel(col, row).unwrap();
assert_eq!(
got[..3],
want[..3],
"{space:?} ({col},{row}) {:?}",
image.decode
);
}
}
let mut eight = image.clone();
eight.bpc = 8;
assert!(!eight.generic_promotion_eligible());
}
}
}
fn rgb_2x1() -> Vec<u8> {
vec![255, 0, 0, 0, 0, 255]
}
#[test]
fn color_key_hides_in_range_texel_paints_out_of_range() {
let mask = ImageMask::ColorKey(Arc::from(vec![[255, 255], [0, 0], [0, 0]]));
let im = img(2, 1, ImageColorSpace::Rgb, rgb_2x1(), Some(mask));
assert_eq!(im.shade(0.25, 0.5), None, "in-range texel is masked out");
let blue = im.shade(0.75, 0.5).expect("out-of-range texel paints");
assert_eq!(&blue[0..3], &[0, 0, 255]);
assert_eq!(blue[3], 255);
}
#[test]
fn color_key_all_components_must_match() {
let mask = ImageMask::ColorKey(Arc::from(vec![[255, 255], [0, 0], [10, 20]]));
let im = img(2, 1, ImageColorSpace::Rgb, rgb_2x1(), Some(mask));
let red = im.shade(0.25, 0.5).expect("partial match does not mask");
assert_eq!(&red[0..3], &[255, 0, 0]);
}
#[test]
fn malformed_color_key_is_ignored() {
let mask = ImageMask::ColorKey(Arc::from(vec![[0, 255], [0, 255]]));
let im = img(2, 1, ImageColorSpace::Rgb, rgb_2x1(), Some(mask));
let red = im
.shade(0.25, 0.5)
.expect("malformed mask ignored, texel paints");
assert_eq!(&red[0..3], &[255, 0, 0]);
}
#[test]
fn stencil_one_masks_zero_paints() {
let mask = stencil(2, 1, vec![0x80], None);
let im = img(2, 1, ImageColorSpace::Rgb, rgb_2x1(), Some(mask));
assert_eq!(im.shade(0.25, 0.5), None, "mask sample 1 → transparent");
let blue = im.shade(0.75, 0.5).expect("mask sample 0 → paints");
assert_eq!(&blue[0..3], &[0, 0, 255]);
}
#[test]
fn minified_stencil_averages_coverage() {
let mask = stencil(8, 1, vec![0b1110_0000], None);
let im = img(1, 1, ImageColorSpace::Rgb, vec![255, 0, 0], Some(mask));
let cov = im.minified_stencil_as_coverage().expect("mask minifies 8x");
assert!(cov.mask.is_none() && cov.smask.is_some());
let px = cov.shade(0.5, 0.5).expect("partly covered pixel paints");
assert_eq!(&px[0..3], &[255, 0, 0]);
assert!((px[3] as i32 - 159).abs() <= 1, "alpha {} != 5/8", px[3]);
let mask = stencil(8, 1, vec![0b1110_0000], Some([1.0, 0.0]));
let im = img(1, 1, ImageColorSpace::Rgb, vec![255, 0, 0], Some(mask));
let px = im
.minified_stencil_as_coverage()
.unwrap()
.shade(0.5, 0.5)
.unwrap();
assert!((px[3] as i32 - 96).abs() <= 1, "alpha {} != 3/8", px[3]);
let mask = stencil(1, 1, vec![0x80], None);
let im = img(1, 1, ImageColorSpace::Rgb, vec![255, 0, 0], Some(mask));
assert!(im.minified_stencil_as_coverage().is_none());
}
#[test]
fn stencil_decode_inverts_polarity() {
let mask = stencil(2, 1, vec![0x80], Some([1.0, 0.0]));
let im = img(2, 1, ImageColorSpace::Rgb, rgb_2x1(), Some(mask));
let red = im
.shade(0.25, 0.5)
.expect("inverted: mask sample 1 → paints");
assert_eq!(&red[0..3], &[255, 0, 0]);
assert_eq!(
im.shade(0.75, 0.5),
None,
"inverted: mask sample 0 → transparent"
);
}
#[test]
fn bilinear_keeps_an_opaque_image_opaque() {
let samples: Vec<u8> = (0..4 * 3 * 3).map(|i| (i * 37 % 256) as u8).collect();
let im = img(4, 3, ImageColorSpace::Rgb, samples, None);
let mut short_of_one = 0;
for i in 0..400 {
for j in 0..300 {
let (fx, fy) = (i as f64 / 133.0, j as f64 / 151.0);
let (tx, ty) = ((fx - fx.floor()) as f32, (fy - fy.floor()) as f32);
let top = 255.0 * (1.0 - tx) + 255.0 * tx;
if ((top * (1.0 - ty) + top * ty) as u8) < 255 {
short_of_one += 1;
}
assert_eq!(im.bilinear(fx, fy).unwrap()[3], 255, "at ({fx}, {fy})");
}
}
assert!(short_of_one > 0, "the f32 blend never fell short of one");
}
#[test]
fn no_mask_paints_normally() {
let im = img(2, 1, ImageColorSpace::Rgb, rgb_2x1(), None);
assert!(im.shade(0.25, 0.5).is_some());
assert!(im.shade(0.75, 0.5).is_some());
}
#[test]
fn prepared_quad_overlap_matches_full_polygon_clipping() {
let footprints = [
[[0.2, 0.3], [2.8, 0.6], [3.4, 2.1], [0.7, 1.8]],
[[0.7, 1.8], [3.4, 2.1], [2.8, 0.6], [0.2, 0.3]],
[[1.2, 1.2], [1.7, 1.3], [1.6, 1.8], [1.1, 1.7]],
[[-0.25, 0.25], [2.25, 0.25], [2.25, 1.75], [-0.25, 1.75]],
];
for vertices in footprints {
let prepared = ConvexQuad::new(vertices).expect("non-degenerate footprint");
for y in -2..5 {
for x in -2..6 {
let x0 = f64::from(x);
let y0 = f64::from(y);
let fast = prepared.rect_overlap_area(x0, x0 + 1.0, y0, y0 + 1.0);
let clipped =
polygon_rect_overlap_area_clipped(&vertices, x0, x0 + 1.0, y0, y0 + 1.0);
assert!(
(fast - clipped).abs() <= 1e-12,
"footprint={vertices:?} texel=({x},{y}) fast={fast} clipped={clipped}"
);
}
}
}
}
#[test]
fn sheared_minification_uses_the_parallelogram_not_its_bounding_box() {
let mut samples = vec![0u8; 5 * 5 * 3];
let white = (2 * 5 + 2) * 3;
samples[white..white + 3].fill(255);
let mut im = img(5, 5, ImageColorSpace::Rgb, samples, None);
im.inv = Matrix {
a: 0.4,
b: 0.0,
c: 0.2,
d: -0.2,
e: 0.0,
f: 0.0,
};
im.footprint = [3.0, 1.0];
let (rgba, taps) = im.area_average(2.0, 2.0).expect("covered texels");
assert_eq!(rgba, [128, 128, 128, 255]);
assert_eq!(taps, 3);
}
#[test]
fn sheared_stencil_minification_averages_exact_coverage() {
let mut im = img(5, 5, ImageColorSpace::Gray, vec![0; 25], None);
im.inv = Matrix {
a: 0.4,
b: 0.0,
c: 0.2,
d: -0.2,
e: 0.0,
f: 0.0,
};
im.footprint = [3.0, 1.0];
im.bpc = 1;
im.is_stencil = true;
im.samples = Arc::from(vec![0xf8, 0xf8, 0xd8, 0xf8, 0xf8]);
im.sample_lut = None;
im.stencil_rgb = [10, 20, 30];
let (rgba, taps) = im.area_average(2.0, 2.0).expect("covered texels");
assert_eq!(rgba, [10, 20, 30, 128]);
assert_eq!(taps, 3);
}
#[test]
fn axis_box_taps_weight_edge_texels_by_overlap() {
let t = axis_box_taps(1.0, 1.0, 4).unwrap();
assert_eq!((t.lo, t.hi), (0, 2));
assert_eq!(t.w_lo, AXIS_TAP_SCALE / 2);
assert_eq!(t.w_hi, AXIS_TAP_SCALE / 2);
assert_eq!(t.total, 2 * AXIS_TAP_SCALE);
assert_eq!(t.weight_at(1), AXIS_TAP_SCALE);
}
#[test]
fn axis_box_taps_clip_to_the_image_and_renormalize() {
let t = axis_box_taps(0.0, 1.0, 4).unwrap();
assert_eq!((t.lo, t.hi), (0, 1));
assert_eq!(t.w_lo, AXIS_TAP_SCALE);
assert_eq!(t.w_hi, AXIS_TAP_SCALE / 2);
assert_eq!(t.total, AXIS_TAP_SCALE + AXIS_TAP_SCALE / 2);
}
#[test]
fn area_average_weights_partial_edge_texels() {
let mut im = img(3, 1, ImageColorSpace::Gray, vec![0, 255, 0], None);
im.footprint = [2.0, 1.0];
assert_eq!(im.shade(0.5, 0.5), Some([128, 128, 128, 255]));
}
#[test]
fn one_bit_minified_average_weights_edges_fractionally() {
let color_space = ImageColorSpace::Gray;
let mut im = img(3, 1, color_space.clone(), vec![0b0100_0000], None);
im.bpc = 1;
im.sample_lut = build_sample_lut(1, &color_space, None, false);
im.footprint = [2.0, 1.0];
assert_eq!(im.shade(0.5, 0.5), Some([128, 128, 128, 255]));
}
#[test]
fn minified_bilevel_soft_mask_averages_coverage_and_applies_decode() {
let sm = ImageSMask {
width: 3,
height: 1,
bits_per_component: 1,
decode: Some(Arc::from(vec![[1.0, 0.0]])),
samples: Arc::from(vec![0b1000_0000]),
codec: None,
codec_data: None,
codec_parms: None,
};
let filtered = sample_smask(&sm, 0.5, 0.5, [2.0, 1.0]);
let nearest = sample_smask(&sm, 0.5, 0.5, [1.0, 1.0]);
assert!((filtered - 0.75).abs() < 1e-6, "{filtered}");
assert_eq!(nearest, 1.0);
}
#[test]
fn one_bit_range_count_handles_partial_and_full_bytes() {
let data = [0b1011_0010, 0b1110_0001, 0b0101_0101];
for start in 0..24 {
for len in 0..=24 - start {
let expected = (start..start + len)
.map(|bit| ((data[bit / 8] >> (7 - bit % 8)) & 1) as u32)
.sum();
assert_eq!(
count_one_bits(&data, start, len),
expected,
"start={start} len={len}"
);
}
}
}
}