alpha-blend 0.2.2

Alpha blending and compositing
Documentation
//! Alpha blending using separable blend modes.
//!
//! This module provides a [`SeparableBlendMode`] implementation of the blend modes ("mixing
//! functions") defined by the [W3C Compositing and Blending Level 1] specification, as opposed
//! to the Porter-Duff compositing operators in [`crate::porter_duff`].
//!
//! A Porter-Duff operator decides *how much* of the source and destination contribute to the
//! result; a blend mode decides *how* their colors are mixed before that compositing happens.
//! The two are combined using the standard separable compositing formula (see
//! [`RgbaBlend::apply`] on [`SeparableBlendMode`]).
//!
//! Only the modes required by [retroglyph#112] are implemented: [`Screen`], [`ColorDodge`],
//! [`ColorBurn`], and [`Overlay`].
//!
//! [W3C Compositing and Blending Level 1]: https://www.w3.org/TR/compositing-1/#blending
//! [retroglyph#112]: https://github.com/crates-lurey-io/retroglyph/issues/112
//! [`Screen`]: SeparableBlendMode::Screen
//! [`ColorDodge`]: SeparableBlendMode::ColorDodge
//! [`ColorBurn`]: SeparableBlendMode::ColorBurn
//! [`Overlay`]: SeparableBlendMode::Overlay

use crate::{
    RgbaBlend,
    rgba::{F32x4Rgba, Rgba},
};

/// A separable blend mode as defined by the [W3C Compositing and Blending Level 1] spec.
///
/// Each variant is a per-channel mixing function `B(Cb, Cs)` where `Cb` is the backdrop
/// (destination) channel and `Cs` is the source channel, both in straight-alpha `0.0..=1.0`.
/// Use [`SeparableBlendMode::mix`] to evaluate a single channel, or the [`RgbaBlend`]
/// implementation to composite two full RGBA colors.
///
/// [W3C Compositing and Blending Level 1]: https://www.w3.org/TR/compositing-1/#blending
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SeparableBlendMode {
    /// `Cb + Cs - Cb * Cs`
    ///
    /// The complement of multiplying the complements of the backdrop and source; always
    /// results in a color at least as light as either input.
    Screen,

    /// Brightens the backdrop to reflect the source.
    ///
    /// ```text
    /// if Cb == 0 { 0 }
    /// else if Cs == 1 { 1 }
    /// else { min(1, Cb / (1 - Cs)) }
    /// ```
    ColorDodge,

    /// Darkens the backdrop to reflect the source.
    ///
    /// ```text
    /// if Cb == 1 { 1 }
    /// else if Cs == 0 { 0 }
    /// else { 1 - min(1, (1 - Cb) / Cs) }
    /// ```
    ColorBurn,

    /// Multiplies or screens the colors, depending on the backdrop.
    ///
    /// Equivalent to `HardLight(Cs, Cb)`:
    ///
    /// ```text
    /// if Cb <= 0.5 { 2 * Cb * Cs }
    /// else { 1 - 2 * (1 - Cb) * (1 - Cs) }
    /// ```
    Overlay,
}

impl SeparableBlendMode {
    /// Evaluates this blend mode's per-channel mixing function `B(Cb, Cs)`.
    ///
    /// `cb` is the backdrop (destination) channel and `cs` is the source channel, both expected
    /// to be in `0.0..=1.0`. Returns a value in `0.0..=1.0`.
    #[must_use]
    #[allow(clippy::float_cmp, clippy::suboptimal_flops)]
    pub fn mix(self, cb: f32, cs: f32) -> f32 {
        match self {
            Self::Screen => cb + cs - cb * cs,
            Self::ColorDodge => {
                if cb == 0.0 {
                    0.0
                } else if cs == 1.0 {
                    1.0
                } else {
                    (cb / (1.0 - cs)).min(1.0)
                }
            }
            Self::ColorBurn => {
                if cb == 1.0 {
                    1.0
                } else if cs == 0.0 {
                    0.0
                } else {
                    1.0 - ((1.0 - cb) / cs).min(1.0)
                }
            }
            Self::Overlay => {
                if cb <= 0.5 {
                    2.0 * cb * cs
                } else {
                    1.0 - 2.0 * (1.0 - cb) * (1.0 - cs)
                }
            }
        }
    }
}

impl RgbaBlend for SeparableBlendMode {
    type Channel = f32;

    /// Composites `src` over `dst` using this blend mode's mixing function.
    ///
    /// Follows the standard (premultiplied) separable compositing formula from the
    /// [W3C Compositing and Blending Level 1] spec:
    ///
    /// ```text
    /// Co = Cs * as * (1 - ab) + Cb * ab * (1 - as) + as * ab * B(Cb, Cs)
    /// ao = as + ab - as * ab
    /// ```
    ///
    /// where `Co`/`ao` are premultiplied by `ao`; both inputs and the returned color use
    /// straight alpha, matching the rest of this crate.
    ///
    /// [W3C Compositing and Blending Level 1]: https://www.w3.org/TR/compositing-1/#blending
    #[allow(clippy::suboptimal_flops)]
    fn apply(&self, src: Rgba<Self::Channel>, dst: Rgba<Self::Channel>) -> Rgba<Self::Channel> {
        let src_pm = src.premultiply();
        let dst_pm = dst.premultiply();
        let src_a = src.alpha();
        let dst_a = dst.alpha();
        let out_a = src_a + dst_a - src_a * dst_a;

        let mix_channel = |cb: f32, cs: f32| self.mix(cb, cs);

        let r = src_pm.r * (1.0 - dst_a)
            + dst_pm.r * (1.0 - src_a)
            + src_a * dst_a * mix_channel(dst.r, src.r);
        let g = src_pm.g * (1.0 - dst_a)
            + dst_pm.g * (1.0 - src_a)
            + src_a * dst_a * mix_channel(dst.g, src.g);
        let b = src_pm.b * (1.0 - dst_a)
            + dst_pm.b * (1.0 - src_a)
            + src_a * dst_a * mix_channel(dst.b, src.b);

        F32x4Rgba::new(r, g, b, out_a).unpremultiply()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // --- Per-channel `mix` formulas ---

    #[test]
    #[allow(clippy::float_cmp)]
    fn mix_screen() {
        let cases: &[(f32, f32, f32)] = &[
            (0.0, 0.0, 0.0),
            (1.0, 1.0, 1.0),
            (0.4, 0.6, 0.76),
            (1.0, 0.0, 1.0),
            (0.0, 1.0, 1.0),
        ];
        for &(cb, cs, expected) in cases {
            let out = SeparableBlendMode::Screen.mix(cb, cs);
            assert!((out - expected).abs() < 1e-6, "cb={cb} cs={cs}: got {out}");
        }
    }

    #[test]
    #[allow(clippy::float_cmp)]
    fn mix_color_dodge() {
        let cases: &[(f32, f32, f32)] = &[
            (0.0, 0.5, 0.0),  // Cb == 0
            (0.5, 1.0, 1.0),  // Cs == 1
            (0.5, 0.5, 1.0),  // min(1, 0.5 / 0.5) == 1.0
            (0.25, 0.5, 0.5), // min(1, 0.25 / 0.5) == 0.5
            (0.0, 1.0, 0.0),  // Cb == 0 takes priority over Cs == 1
        ];
        for &(cb, cs, expected) in cases {
            let out = SeparableBlendMode::ColorDodge.mix(cb, cs);
            assert!((out - expected).abs() < 1e-6, "cb={cb} cs={cs}: got {out}");
        }
    }

    #[test]
    #[allow(clippy::float_cmp)]
    fn mix_color_burn() {
        let cases: &[(f32, f32, f32)] = &[
            (1.0, 0.5, 1.0),  // Cb == 1
            (0.5, 0.0, 0.0),  // Cs == 0
            (0.5, 0.5, 0.0),  // 1 - min(1, 0.5 / 0.5) == 0.0
            (0.75, 0.5, 0.5), // 1 - min(1, 0.25 / 0.5) == 0.5
            (1.0, 0.0, 1.0),  // Cb == 1 takes priority over Cs == 0
        ];
        for &(cb, cs, expected) in cases {
            let out = SeparableBlendMode::ColorBurn.mix(cb, cs);
            assert!((out - expected).abs() < 1e-6, "cb={cb} cs={cs}: got {out}");
        }
    }

    #[test]
    #[allow(clippy::float_cmp)]
    fn mix_overlay() {
        let cases: &[(f32, f32, f32)] = &[
            (0.0, 0.0, 0.0),
            (1.0, 1.0, 1.0),
            (0.5, 0.5, 0.5),   // boundary: Cb <= 0.5 branch
            (0.25, 0.5, 0.25), // 2 * 0.25 * 0.5
            (0.75, 0.5, 0.75), // 1 - 2 * 0.25 * 0.5
        ];
        for &(cb, cs, expected) in cases {
            let out = SeparableBlendMode::Overlay.mix(cb, cs);
            assert!((out - expected).abs() < 1e-6, "cb={cb} cs={cs}: got {out}");
        }
    }

    // --- Full RGBA compositing (`RgbaBlend::apply`) ---

    /// With both inputs fully opaque, compositing reduces to the raw `mix` formula per channel.
    #[test]
    fn apply_opaque_matches_mix() {
        let src = F32x4Rgba::new(0.1, 0.2, 0.3, 1.0);
        let dst = F32x4Rgba::new(0.4, 0.5, 0.6, 1.0);

        let modes = [
            SeparableBlendMode::Screen,
            SeparableBlendMode::ColorDodge,
            SeparableBlendMode::ColorBurn,
            SeparableBlendMode::Overlay,
        ];
        for mode in modes {
            let out = mode.apply(src, dst);
            assert!((out.a - 1.0).abs() < 1e-6);
            assert!((out.r - mode.mix(dst.r, src.r)).abs() < 1e-5, "{mode:?} r");
            assert!((out.g - mode.mix(dst.g, src.g)).abs() < 1e-5, "{mode:?} g");
            assert!((out.b - mode.mix(dst.b, src.b)).abs() < 1e-5, "{mode:?} b");
        }
    }

    #[test]
    fn apply_screen_partial_alpha() {
        let src = F32x4Rgba::new(0.2, 0.6, 0.8, 0.5);
        let dst = F32x4Rgba::new(0.9, 0.3, 0.1, 0.4);
        let out = SeparableBlendMode::Screen.apply(src, dst);
        let expected = F32x4Rgba::new(0.605_714_3, 0.548_571_4, 0.605_714_3, 0.7);
        assert!((out.r - expected.r).abs() < 1e-5);
        assert!((out.g - expected.g).abs() < 1e-5);
        assert!((out.b - expected.b).abs() < 1e-5);
        assert!((out.a - expected.a).abs() < 1e-5);
    }

    #[test]
    fn apply_color_dodge_partial_alpha() {
        let src = F32x4Rgba::new(0.2, 0.6, 0.8, 0.5);
        let dst = F32x4Rgba::new(0.9, 0.3, 0.1, 0.4);
        let out = SeparableBlendMode::ColorDodge.apply(src, dst);
        let expected = F32x4Rgba::new(0.628_571_4, 0.557_142_9, 0.514_285_7, 0.7);
        assert!((out.r - expected.r).abs() < 1e-5);
        assert!((out.g - expected.g).abs() < 1e-5);
        assert!((out.b - expected.b).abs() < 1e-5);
        assert!((out.a - expected.a).abs() < 1e-5);
    }

    #[test]
    fn apply_color_burn_partial_alpha() {
        let src = F32x4Rgba::new(0.2, 0.6, 0.8, 0.5);
        let dst = F32x4Rgba::new(0.9, 0.3, 0.1, 0.4);
        let out = SeparableBlendMode::ColorBurn.apply(src, dst);
        let expected = F32x4Rgba::new(0.485_714_3, 0.342_857_1, 0.371_428_6, 0.7);
        assert!((out.r - expected.r).abs() < 1e-5);
        assert!((out.g - expected.g).abs() < 1e-5);
        assert!((out.b - expected.b).abs() < 1e-5);
        assert!((out.a - expected.a).abs() < 1e-5);
    }

    #[test]
    fn apply_overlay_partial_alpha() {
        let src = F32x4Rgba::new(0.2, 0.6, 0.8, 0.5);
        let dst = F32x4Rgba::new(0.9, 0.3, 0.1, 0.4);
        let out = SeparableBlendMode::Overlay.apply(src, dst);
        let expected = F32x4Rgba::new(0.582_857_1, 0.445_714_3, 0.417_142_9, 0.7);
        assert!((out.r - expected.r).abs() < 1e-5);
        assert!((out.g - expected.g).abs() < 1e-5);
        assert!((out.b - expected.b).abs() < 1e-5);
        assert!((out.a - expected.a).abs() < 1e-5);
    }

    #[test]
    fn apply_both_transparent_is_transparent() {
        let src = F32x4Rgba::TRANSPARENT;
        let dst = F32x4Rgba::TRANSPARENT;
        for mode in [
            SeparableBlendMode::Screen,
            SeparableBlendMode::ColorDodge,
            SeparableBlendMode::ColorBurn,
            SeparableBlendMode::Overlay,
        ] {
            assert_eq!(mode.apply(src, dst), F32x4Rgba::TRANSPARENT);
        }
    }

    #[test]
    fn apply_slice_matches_individual() {
        let src = [
            F32x4Rgba::new(0.2, 0.6, 0.8, 0.5),
            F32x4Rgba::new(0.1, 0.9, 0.4, 1.0),
        ];
        let dst = [
            F32x4Rgba::new(0.9, 0.3, 0.1, 0.4),
            F32x4Rgba::new(0.5, 0.5, 0.5, 1.0),
        ];

        let mut batch = dst;
        SeparableBlendMode::Overlay.apply_slice(&src, &mut batch);

        for (i, (s, d)) in src.iter().zip(dst.iter()).enumerate() {
            let expected = SeparableBlendMode::Overlay.apply(*s, *d);
            assert_eq!(batch[i], expected);
        }
    }
}