Skip to main content

alpha_blend/
composite.rs

1//! Combining a blend mode with a compositing operator.
2//!
3//! [`Composite`] is the pairing the [W3C Compositing and Blending Level 1] spec actually
4//! describes: a [`BlendMode`] says how the source and backdrop colors are mixed, a
5//! [`CompositeMode`] says how much of each survives, and the two are independent.
6//!
7//! [W3C Compositing and Blending Level 1]: https://www.w3.org/TR/compositing-1/#blending
8
9use crate::{
10    BlendMode, CompositeMode, RgbaBlend,
11    channel::Channel,
12    porter_duff::Coefficients,
13    rgba::{Premultiplied, Rgba},
14};
15
16/// A [`BlendMode`] paired with a [`CompositeMode`].
17///
18/// Constructed with [`Composite::new`], or converted from either half when the other should be
19/// the default:
20///
21/// ```rust
22/// use alpha_blend::{BlendMode, Composite, CompositeMode};
23///
24/// let multiply_over = Composite::new(BlendMode::Multiply, CompositeMode::SourceOver);
25/// assert_eq!(Composite::from(BlendMode::Multiply), multiply_over);
26/// assert_eq!(Composite::default(), Composite::NORMAL_OVER);
27/// ```
28///
29/// The fields are private so that a future non-separable blend mode or color space can be added
30/// without a breaking change; use the accessors and [`Composite::new`].
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
32pub struct Composite {
33    blend: BlendMode,
34    op: CompositeMode,
35}
36
37impl From<BlendMode> for Composite {
38    fn from(blend: BlendMode) -> Self {
39        Self::new(blend, CompositeMode::SourceOver)
40    }
41}
42
43impl From<CompositeMode> for Composite {
44    fn from(op: CompositeMode) -> Self {
45        Self::new(BlendMode::Normal, op)
46    }
47}
48
49impl Composite {
50    /// Plain source-over compositing with no blending. The default, and by far the common case.
51    pub const NORMAL_OVER: Self = Self::new(BlendMode::Normal, CompositeMode::SourceOver);
52
53    /// Pairs a blend mode with a compositing operator.
54    #[must_use]
55    pub const fn new(blend: BlendMode, op: CompositeMode) -> Self {
56        Self { blend, op }
57    }
58
59    /// Returns the blend mode.
60    #[must_use]
61    pub const fn blend(self) -> BlendMode {
62        self.blend
63    }
64
65    /// Returns the compositing operator.
66    #[must_use]
67    pub const fn op(self) -> CompositeMode {
68        self.op
69    }
70
71    /// Composites `src` over `dst`, returning a premultiplied color.
72    ///
73    /// This is the primitive; [`RgbaBlend::apply`] is this followed by
74    /// [`Premultiplied::unpremultiply`]. Prefer this one when the result feeds another
75    /// composite, because for integer channels the unpremultiply is lossy.
76    ///
77    /// Implements the W3C general formula. `Cs`, `Cb`, `as` and `ab` are straight-alpha inputs;
78    /// `co` is premultiplied by `ao`:
79    ///
80    /// ```text
81    /// Cs' = (1 - ab) * Cs + ab * B(Cb, Cs)
82    /// co  = as * Fa * Cs' + ab * Fb * Cb
83    /// ao  = as * Fa + ab * Fb
84    /// ```
85    ///
86    /// ## Accuracy
87    ///
88    /// For [`Composite::NORMAL_OVER`] with an opaque destination, the `u8` result is exact and
89    /// bit-for-bit identical to [`U8x4Rgba::source_over`](crate::rgba::U8x4Rgba::source_over).
90    /// Other combinations round at most twice for integer channels and can differ from the
91    /// exact rational result by up to 2 LSB.
92    #[must_use]
93    pub fn composite<C: Channel>(self, src: Rgba<C>, dst: Rgba<C>) -> Premultiplied<Rgba<C>> {
94        let (src_a, dst_a) = (src.a, dst.a);
95        let Coefficients { src: fa, dst: fb } = self.op.coefficients(src_a, dst_a);
96
97        // Fold `as * Fa` and `ab * Fb` once instead of per channel.
98        let weight_src = src_a.scale(fa);
99        let weight_dst = dst_a.scale(fb);
100
101        let channel = |cb: C, cs: C| {
102            // The blend only applies where the backdrop actually is; elsewhere the source
103            // shows through unmixed. That is the `(1 - ab) * Cs + ab * B(Cb, Cs)` term.
104            let blended = C::sum_of_products(dst_a.complement(), cs, dst_a, self.blend.mix(cb, cs));
105            C::sum_of_products(weight_src, blended, weight_dst, cb)
106        };
107
108        Premultiplied::from_premultiplied(Rgba::new(
109            channel(dst.r, src.r),
110            channel(dst.g, src.g),
111            channel(dst.b, src.b),
112            C::sum_of_products(src_a, fa, dst_a, fb),
113        ))
114    }
115}
116
117impl<C: Channel> RgbaBlend<C> for Composite {
118    fn apply(&self, src: Rgba<C>, dst: Rgba<C>) -> Rgba<C> {
119        self.composite(src, dst).unpremultiply()
120    }
121}
122
123impl<C: Channel> RgbaBlend<C> for CompositeMode {
124    /// Composites with [`BlendMode::Normal`].
125    fn apply(&self, src: Rgba<C>, dst: Rgba<C>) -> Rgba<C> {
126        Composite::new(BlendMode::Normal, *self).apply(src, dst)
127    }
128}
129
130impl<C: Channel> RgbaBlend<C> for BlendMode {
131    /// Blends with [`CompositeMode::SourceOver`].
132    fn apply(&self, src: Rgba<C>, dst: Rgba<C>) -> Rgba<C> {
133        Composite::new(*self, CompositeMode::SourceOver).apply(src, dst)
134    }
135}
136
137#[cfg(test)]
138#[allow(
139    clippy::cast_possible_truncation,
140    clippy::cast_sign_loss,
141    clippy::float_cmp,
142    clippy::suboptimal_flops
143)]
144mod tests {
145    use super::*;
146    use crate::rgba::{F32x4Rgba, U8x4Rgba};
147
148    fn assert_close(got: F32x4Rgba, want: F32x4Rgba, what: &str) {
149        assert!(
150            (got.r - want.r).abs() < 1e-5
151                && (got.g - want.g).abs() < 1e-5
152                && (got.b - want.b).abs() < 1e-5
153                && (got.a - want.a).abs() < 1e-5,
154            "{what}: got {got}, want {want}",
155        );
156    }
157
158    #[test]
159    fn default_and_conversions() {
160        assert_eq!(Composite::default(), Composite::NORMAL_OVER);
161        assert_eq!(Composite::NORMAL_OVER.blend(), BlendMode::Normal);
162        assert_eq!(Composite::NORMAL_OVER.op(), CompositeMode::SourceOver);
163        assert_eq!(
164            Composite::from(BlendMode::Multiply),
165            Composite::new(BlendMode::Multiply, CompositeMode::SourceOver),
166        );
167        assert_eq!(
168            Composite::from(CompositeMode::Xor),
169            Composite::new(BlendMode::Normal, CompositeMode::Xor),
170        );
171    }
172
173    /// The load-bearing cross-check for retroglyph#547: the generic composite path and the
174    /// specialized integer `source_over` must not be able to disagree. Exact, for every
175    /// source alpha and a representative spread of colors, against an opaque destination.
176    #[test]
177    fn u8_normal_over_matches_source_over_exactly() {
178        for src_a in 0..=255u8 {
179            for s in (0..=255u8).step_by(5) {
180                for d in (0..=255u8).step_by(5) {
181                    let src = U8x4Rgba::new(s, 255 - s, s, src_a);
182                    let dst = U8x4Rgba::new(d, d, 255 - d, 255);
183                    assert_eq!(
184                        Composite::NORMAL_OVER.apply(src, dst),
185                        src.source_over(dst),
186                        "src={src} dst={dst}",
187                    );
188                }
189            }
190        }
191    }
192
193    /// With a translucent destination the generic path is still correct, but it is correct in
194    /// *premultiplied* space; comparing straight-alpha output to `source_over` would only
195    /// measure the 8-bit unpremultiply, which is unbounded as alpha falls. So compare the
196    /// premultiplied result to an `f64` oracle instead.
197    #[test]
198    fn u8_normal_over_is_correct_for_translucent_dst() {
199        let reference = |src: U8x4Rgba, dst: U8x4Rgba| {
200            let (sa, da) = (f64::from(src.a) / 255.0, f64::from(dst.a) / 255.0);
201            let ch = |s: u8, d: u8| {
202                let co = f64::from(s) / 255.0 * sa + f64::from(d) / 255.0 * da * (1.0 - sa);
203                (co * 255.0 + 0.5) as u8
204            };
205            U8x4Rgba::new(
206                ch(src.r, dst.r),
207                ch(src.g, dst.g),
208                ch(src.b, dst.b),
209                ((sa + da * (1.0 - sa)) * 255.0 + 0.5) as u8,
210            )
211        };
212
213        for src_a in (0..=255u8).step_by(3) {
214            for dst_a in (0..=255u8).step_by(3) {
215                for v in (0..=255u8).step_by(15) {
216                    let src = U8x4Rgba::new(v, 200, 30, src_a);
217                    let dst = U8x4Rgba::new(10, v, 240, dst_a);
218                    let got = Composite::NORMAL_OVER.composite(src, dst).get();
219                    let want = reference(src, dst);
220                    assert!(
221                        got.r.abs_diff(want.r) <= 1
222                            && got.g.abs_diff(want.g) <= 1
223                            && got.b.abs_diff(want.b) <= 1
224                            && got.a.abs_diff(want.a) <= 1,
225                        "src={src} dst={dst}: got {got}, want {want}",
226                    );
227                    assert_eq!(
228                        got.a,
229                        src.source_over(dst).a,
230                        "alpha agrees with the direct path exactly; src={src} dst={dst}",
231                    );
232                }
233            }
234        }
235    }
236
237    /// Opaque over opaque reduces to the raw mixing function for every blend mode.
238    #[test]
239    fn opaque_over_opaque_is_the_mix_function() {
240        let src = F32x4Rgba::new(0.1, 0.2, 0.3, 1.0);
241        let dst = F32x4Rgba::new(0.4, 0.5, 0.6, 1.0);
242        for mode in BlendMode::ALL {
243            let out = mode.apply(src, dst);
244            assert_close(
245                out,
246                F32x4Rgba::new(
247                    mode.mix(dst.r, src.r),
248                    mode.mix(dst.g, src.g),
249                    mode.mix(dst.b, src.b),
250                    1.0,
251                ),
252                &format!("{mode:?}"),
253            );
254        }
255    }
256
257    /// Compositing onto or from nothing must not invent color.
258    #[test]
259    fn transparent_inputs() {
260        for mode in BlendMode::ALL {
261            assert_eq!(
262                mode.apply(F32x4Rgba::TRANSPARENT, F32x4Rgba::TRANSPARENT),
263                F32x4Rgba::TRANSPARENT,
264                "{mode:?}",
265            );
266            // A transparent source leaves the destination alone under SourceOver.
267            assert_close(
268                mode.apply(F32x4Rgba::TRANSPARENT, F32x4Rgba::new(0.2, 0.4, 0.6, 1.0)),
269                F32x4Rgba::new(0.2, 0.4, 0.6, 1.0),
270                &format!("{mode:?} transparent src"),
271            );
272            // An opaque source over nothing is just the source.
273            assert_close(
274                mode.apply(F32x4Rgba::new(0.2, 0.4, 0.6, 1.0), F32x4Rgba::TRANSPARENT),
275                F32x4Rgba::new(0.2, 0.4, 0.6, 1.0),
276                &format!("{mode:?} transparent dst"),
277            );
278        }
279    }
280
281    /// The Porter-Duff operators, with both inputs opaque, reduce to picking one input or
282    /// clearing. Transcribed from the operator definitions, not from the implementation.
283    #[test]
284    fn opaque_porter_duff_table() {
285        let src = F32x4Rgba::new(0.1, 0.2, 0.3, 1.0);
286        let dst = F32x4Rgba::new(0.4, 0.5, 0.6, 1.0);
287        let cases: &[(CompositeMode, F32x4Rgba)] = &[
288            (CompositeMode::Clear, F32x4Rgba::TRANSPARENT),
289            (CompositeMode::Source, src),
290            (CompositeMode::Destination, dst),
291            (CompositeMode::SourceOver, src),
292            (CompositeMode::DestinationOver, dst),
293            (CompositeMode::SourceIn, src),
294            (CompositeMode::DestinationIn, dst),
295            (CompositeMode::SourceOut, F32x4Rgba::TRANSPARENT),
296            (CompositeMode::DestinationOut, F32x4Rgba::TRANSPARENT),
297            (CompositeMode::SourceAtop, src),
298            (CompositeMode::DestinationAtop, dst),
299            (CompositeMode::Xor, F32x4Rgba::TRANSPARENT),
300            (CompositeMode::Plus, F32x4Rgba::new(0.5, 0.7, 0.9, 1.0)),
301        ];
302        assert_eq!(cases.len(), CompositeMode::ALL.len(), "table is complete");
303        for &(mode, want) in cases {
304            assert_close(mode.apply(src, dst), want, &format!("{mode:?}"));
305        }
306    }
307
308    /// `Plus` used to return `a = 2.0` and require a manual clamp.
309    #[test]
310    fn plus_saturates_instead_of_overflowing() {
311        let out = CompositeMode::Plus.apply(
312            F32x4Rgba::new(0.8, 0.8, 0.8, 1.0),
313            F32x4Rgba::new(0.8, 0.8, 0.8, 1.0),
314        );
315        assert_eq!(out.a, 1.0);
316        assert!(out.r <= 1.0);
317        assert_eq!(out, out.clamp(), "already in range");
318    }
319
320    /// The alpha bug fixed in 0.2.1 for the `u8` path, now also fixed for `f32`: source-over
321    /// alpha is `as + ab * (1 - as)`, not `as * as + ab * (1 - as)`.
322    #[test]
323    fn source_over_alpha_is_correct_for_f32() {
324        let src = F32x4Rgba::new(1.0, 0.0, 0.0, 0.5);
325        let dst = F32x4Rgba::new(0.0, 0.0, 1.0, 1.0);
326        let out = CompositeMode::SourceOver.apply(src, dst);
327        assert_close(out, F32x4Rgba::new(0.5, 0.0, 0.5, 1.0), "src over");
328    }
329
330    /// Blending is only visible where the backdrop is; a partially transparent backdrop
331    /// interpolates between the blended and the raw source.
332    #[test]
333    fn blend_is_weighted_by_backdrop_alpha() {
334        let src = F32x4Rgba::new(0.5, 0.5, 0.5, 1.0);
335        // Multiply against a half-transparent black backdrop: half blended (0.0), half raw
336        // source (0.5), then composited over.
337        let dst = F32x4Rgba::new(0.0, 0.0, 0.0, 0.5);
338        let out = Composite::new(BlendMode::Multiply, CompositeMode::SourceOver).apply(src, dst);
339        assert_close(out, F32x4Rgba::new(0.25, 0.25, 0.25, 1.0), "multiply");
340    }
341
342    /// `Normal` composited with each operator must equal that operator used on its own.
343    #[test]
344    fn normal_blend_is_the_identity_for_every_operator() {
345        let src = F32x4Rgba::new(0.1, 0.7, 0.3, 0.4);
346        let dst = F32x4Rgba::new(0.8, 0.2, 0.6, 0.9);
347        for op in CompositeMode::ALL {
348            assert_eq!(
349                Composite::new(BlendMode::Normal, op).apply(src, dst),
350                op.apply(src, dst),
351                "{op:?}",
352            );
353        }
354    }
355
356    /// `SourceOver` composited with each blend mode must equal that blend mode on its own.
357    #[test]
358    fn source_over_is_the_identity_for_every_blend_mode() {
359        let src = F32x4Rgba::new(0.1, 0.7, 0.3, 0.4);
360        let dst = F32x4Rgba::new(0.8, 0.2, 0.6, 0.9);
361        for blend in BlendMode::ALL {
362            assert_eq!(
363                Composite::new(blend, CompositeMode::SourceOver).apply(src, dst),
364                blend.apply(src, dst),
365                "{blend:?}",
366            );
367        }
368    }
369
370    /// Integer and float compositing must describe the same operation.
371    #[test]
372    fn u8_and_f32_composites_agree() {
373        let src = U8x4Rgba::new(26, 179, 77, 102);
374        let dst = U8x4Rgba::new(204, 51, 153, 230);
375        for blend in BlendMode::ALL {
376            for op in CompositeMode::ALL {
377                let composite = Composite::new(blend, op);
378                // Compare *premultiplied* results. This is the math under test; `apply` adds a
379                // lossy unpremultiply on top, which at low alpha amplifies a sub-LSB
380                // difference into several LSB and would only measure that division.
381                let int = composite.composite(src, dst).get();
382                let flt: F32x4Rgba = composite
383                    .composite(F32x4Rgba::from(src), F32x4Rgba::from(dst))
384                    .get();
385                let flt = U8x4Rgba::from(flt);
386                assert!(
387                    int.r.abs_diff(flt.r) <= 2
388                        && int.g.abs_diff(flt.g) <= 2
389                        && int.b.abs_diff(flt.b) <= 2
390                        && int.a.abs_diff(flt.a) <= 1,
391                    "{blend:?} + {op:?}: u8 {int}, f32 {flt}",
392                );
393            }
394        }
395    }
396
397    /// The straight-alpha `u8` path additionally carries the unpremultiply error, which grows
398    /// without bound as alpha falls. Pinned so the `Premultiplied` docs stay honest.
399    #[test]
400    fn u8_unpremultiply_error_is_the_dominant_term_at_low_alpha() {
401        let src = U8x4Rgba::new(26, 179, 77, 8);
402        let dst = U8x4Rgba::new(204, 51, 153, 8);
403        let composite = Composite::new(BlendMode::Multiply, CompositeMode::SourceOut);
404        let premultiplied = composite.composite(src, dst).get();
405        let straight = composite.apply(src, dst);
406        assert!(
407            straight.r.abs_diff(premultiplied.r) > 2,
408            "unpremultiply at alpha {} should be visible",
409            straight.a,
410        );
411    }
412
413    /// `composite` returns premultiplied color; `apply` is that plus an unpremultiply.
414    #[test]
415    fn composite_returns_premultiplied() {
416        let src = F32x4Rgba::new(1.0, 1.0, 1.0, 0.5);
417        let dst = F32x4Rgba::TRANSPARENT;
418        let premultiplied = Composite::NORMAL_OVER.composite(src, dst);
419        assert_close(
420            premultiplied.get(),
421            F32x4Rgba::new(0.5, 0.5, 0.5, 0.5),
422            "premul",
423        );
424        assert_close(
425            Composite::NORMAL_OVER.apply(src, dst),
426            F32x4Rgba::new(1.0, 1.0, 1.0, 0.5),
427            "straight",
428        );
429    }
430
431    #[test]
432    fn apply_slice_matches_individual() {
433        let src = [
434            F32x4Rgba::new(0.2, 0.6, 0.8, 0.5),
435            F32x4Rgba::new(0.1, 0.9, 0.4, 1.0),
436        ];
437        let dst = [
438            F32x4Rgba::new(0.9, 0.3, 0.1, 0.4),
439            F32x4Rgba::new(0.5, 0.5, 0.5, 1.0),
440        ];
441        let mut batch = dst;
442        BlendMode::Overlay.apply_slice(&src, &mut batch);
443        for (i, (s, d)) in src.iter().zip(dst.iter()).enumerate() {
444            assert_eq!(batch[i], BlendMode::Overlay.apply(*s, *d));
445        }
446    }
447
448    #[test]
449    fn apply_slice_works_for_u8() {
450        let src = [U8x4Rgba::new(255, 0, 0, 128), U8x4Rgba::WHITE];
451        let dst = [U8x4Rgba::BLACK; 2];
452        let mut batch = dst;
453        CompositeMode::SourceOver.apply_slice(&src, &mut batch);
454        assert_eq!(batch[0], src[0].source_over(dst[0]));
455        assert_eq!(batch[1], U8x4Rgba::WHITE);
456    }
457
458    #[test]
459    #[should_panic(expected = "must have the same length")]
460    fn apply_slice_panics_on_mismatched_lengths() {
461        let src = [F32x4Rgba::new(0.0, 0.0, 0.0, 0.0)];
462        let mut dst = [F32x4Rgba::WHITE; 2];
463        CompositeMode::SourceOver.apply_slice(&src, &mut dst);
464    }
465
466    #[test]
467    fn composite_hash() {
468        use std::collections::HashSet;
469        let mut set = HashSet::new();
470        set.insert(Composite::NORMAL_OVER);
471        set.insert(Composite::default());
472        assert_eq!(set.len(), 1);
473        set.insert(Composite::from(BlendMode::Multiply));
474        assert_eq!(set.len(), 2);
475    }
476}