#![cfg_attr(not(feature = "std"), no_std)]
use crate::{porter_duff::PorterDuff, rgba::Rgba};
pub mod blend_modes;
pub(crate) mod math;
pub mod porter_duff;
pub mod rgba;
pub(crate) mod vec4;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum BlendMode {
Clear,
Source,
Destination,
#[default]
SourceOver,
DestinationOver,
SourceIn,
DestinationIn,
SourceOut,
DestinationOut,
SourceAtop,
DestinationAtop,
Xor,
Plus,
}
impl RgbaBlend for BlendMode {
type Channel = f32;
fn apply(&self, src: Rgba<Self::Channel>, dst: Rgba<Self::Channel>) -> Rgba<Self::Channel> {
let pd: PorterDuff<f32, fn(f32, f32) -> f32> = match self {
Self::Clear => PorterDuff::CLEAR,
Self::Source => PorterDuff::SRC,
Self::Destination => PorterDuff::DST,
Self::SourceOver => PorterDuff::SRC_OVER,
Self::DestinationOver => PorterDuff::DST_OVER,
Self::SourceIn => PorterDuff::SRC_IN,
Self::DestinationIn => PorterDuff::DST_IN,
Self::SourceOut => PorterDuff::SRC_OUT,
Self::DestinationOut => PorterDuff::DST_OUT,
Self::SourceAtop => PorterDuff::SRC_ATOP,
Self::DestinationAtop => PorterDuff::DST_ATOP,
Self::Xor => PorterDuff::XOR,
Self::Plus => PorterDuff::PLUS,
};
pd.apply(src, dst)
}
}
pub trait RgbaBlend {
type Channel: Copy;
fn apply(&self, src: Rgba<Self::Channel>, dst: Rgba<Self::Channel>) -> Rgba<Self::Channel>;
fn apply_slice(&self, src: &[Rgba<Self::Channel>], dst: &mut [Rgba<Self::Channel>]) {
assert_eq!(
src.len(),
dst.len(),
"src and dst slices must have the same length"
);
for (s, d) in src.iter().zip(dst.iter_mut()) {
*d = self.apply(*s, *d);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::rgba::F32x4Rgba;
#[test]
fn blend_mode_default_is_source_over() {
assert_eq!(BlendMode::default(), BlendMode::SourceOver);
}
#[test]
fn apply_slice_matches_individual() {
let src = [
F32x4Rgba::new(1.0, 0.0, 0.0, 0.5),
F32x4Rgba::new(0.0, 1.0, 0.0, 1.0),
];
let dst = [
F32x4Rgba::new(0.0, 0.0, 1.0, 1.0),
F32x4Rgba::new(1.0, 0.0, 0.0, 1.0),
];
let mut batch = dst;
BlendMode::SourceOver.apply_slice(&src, &mut batch);
for (i, (s, d)) in src.iter().zip(dst.iter()).enumerate() {
let expected = BlendMode::SourceOver.apply(*s, *d);
assert_eq!(batch[i], expected);
}
}
#[test]
#[should_panic(expected = "must have the same length")]
fn apply_slice_panics_on_mismatched_lengths() {
let src = [F32x4Rgba::new(0.0, 0.0, 0.0, 0.0)];
let mut dst = [F32x4Rgba::new(1.0, 1.0, 1.0, 1.0); 2];
BlendMode::SourceOver.apply_slice(&src, &mut dst);
}
#[test]
fn blend_mode_hash() {
use std::collections::HashSet;
let mut set = HashSet::new();
set.insert(BlendMode::SourceOver);
set.insert(BlendMode::SourceOver);
assert_eq!(set.len(), 1);
set.insert(BlendMode::Clear);
assert_eq!(set.len(), 2);
}
}