alpha-blend 0.3.0

Alpha blending and compositing
Documentation
//! Alpha blending and compositing in (optionally) zero-dependency Rust.
//!
//! There are three pieces:
//!
//! - A [`CompositeMode`] decides **how much** of the source and destination survive. These are
//!   the Porter-Duff operators: [`SourceOver`](CompositeMode::SourceOver),
//!   [`Xor`](CompositeMode::Xor), and so on.
//! - A [`BlendMode`] decides **how** their colors are mixed. These are the W3C separable blend
//!   modes: [`Multiply`](BlendMode::Multiply), [`Screen`](BlendMode::Screen),
//!   [`SoftLight`](BlendMode::SoftLight), and so on.
//! - A [`Composite`] pairs the two. Either half can be used on its own, in which case the other
//!   takes its default.
//!
//! Everything is generic over [`channel::Channel`], so [`u8`] and [`f32`] pixels go
//! through the same code at their own precision. There is no separate integer implementation to
//! drift out of sync with the float one.
//!
//! All blending assumes **straight (un-premultiplied) alpha** unless documented otherwise. See
//! [`rgba::Premultiplied`] for the other convention.
//!
//! ## Examples
//!
//! ```rust
//! use alpha_blend::{CompositeMode, RgbaBlend, rgba::F32x4Rgba};
//!
//! let src = F32x4Rgba { r: 1.0, g: 0.0, b: 0.0, a: 0.5 }; // Semi-transparent red
//! let dst = F32x4Rgba { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }; // Opaque blue
//! let blended = CompositeMode::SourceOver.apply(src, dst);
//!
//! // Half red over opaque blue: an even mix, still opaque.
//! assert_eq!(blended, F32x4Rgba { r: 0.5, g: 0.0, b: 0.5, a: 1.0 });
//! ```
//!
//! The same operation on `u8` pixels, and with a blend mode applied:
//!
//! ```rust
//! use alpha_blend::{BlendMode, Composite, CompositeMode, RgbaBlend, rgba::U8x4Rgba};
//!
//! let src = U8x4Rgba::new(255, 128, 0, 128);
//! let dst = U8x4Rgba::new(0, 64, 255, 255);
//!
//! // Plain source-over has a dedicated integer fast path.
//! assert_eq!(CompositeMode::SourceOver.apply(src, dst), src.source_over(dst));
//!
//! // Multiply, composited source-over.
//! let multiply = Composite::new(BlendMode::Multiply, CompositeMode::SourceOver);
//! assert_eq!(multiply.apply(src, dst), U8x4Rgba::new(0, 48, 127, 255));
//! ```
//!
//! ## Rounding
//!
//! Integer channels round to nearest, once per operation, from a widened intermediate.
//! `scale(255, 255) == 255`, and compositing an opaque pixel repeatedly is idempotent. See the
//! [`channel`] module docs for the exact rules and why the usual `>> 8` shift trick is not used.
//!
//! ## Features
//!
//! By default, this crate is `no_std` compatible, and uses [`libm`] for some math operations.
//!
//! Either `std` or `libm` must be enabled.
//!
//! ### `bytemuck`
//!
//! Enables the `bytemuck` crate for zero-copy conversions between types.
//!
//! ### `libm`
//!
//! _This feature is enabled by default._
//!
//! Uses the `libm` crate for math operations.
//!
//! ### `libm-arch`
//!
//! _This feature is enabled by default._
//!
//! Enables the `arch` feature of `libm`.
//!
//! ### `std`
//!
//! Uses the standard library for math operations, such as `f32::round`.

#![cfg_attr(not(feature = "std"), no_std)]

use crate::{channel::Channel, rgba::Rgba};

pub mod blend_modes;
pub mod channel;
pub mod composite;
pub(crate) mod math;
pub mod porter_duff;
pub mod rgba;

pub use crate::{blend_modes::BlendMode, composite::Composite, porter_duff::CompositeMode};

/// Blends pixel colors using alpha compositing.
///
/// Implemented by [`Composite`] and, for convenience, by [`BlendMode`] and [`CompositeMode`]
/// on their own. Implement it yourself to provide a specialized or vectorized path; overriding
/// [`RgbaBlend::apply_slice`] is the usual reason to.
pub trait RgbaBlend<C: Channel> {
    /// Blends two colors together, returning a straight-alpha result.
    ///
    /// For integer channels this includes an unpremultiply, which is lossy. Use
    /// [`Composite::composite`] instead when the result feeds another composite.
    fn apply(&self, src: Rgba<C>, dst: Rgba<C>) -> Rgba<C>;

    /// Blend `src` over `dst` in place, pixel by pixel.
    ///
    /// Default impl calls [`apply`](RgbaBlend::apply) in a loop.
    /// Implementations may override with SIMD or other optimized paths.
    ///
    /// # Panics
    ///
    /// If `src` and `dst` have different lengths.
    fn apply_slice(&self, src: &[Rgba<C>], dst: &mut [Rgba<C>]) {
        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);
        }
    }
}