alpha-blend 0.3.0

Alpha blending and compositing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! Combining a blend mode with a compositing operator.
//!
//! [`Composite`] is the pairing the [W3C Compositing and Blending Level 1] spec actually
//! describes: a [`BlendMode`] says how the source and backdrop colors are mixed, a
//! [`CompositeMode`] says how much of each survives, and the two are independent.
//!
//! [W3C Compositing and Blending Level 1]: https://www.w3.org/TR/compositing-1/#blending

use crate::{
    BlendMode, CompositeMode, RgbaBlend,
    channel::Channel,
    porter_duff::Coefficients,
    rgba::{Premultiplied, Rgba},
};

/// A [`BlendMode`] paired with a [`CompositeMode`].
///
/// Constructed with [`Composite::new`], or converted from either half when the other should be
/// the default:
///
/// ```rust
/// use alpha_blend::{BlendMode, Composite, CompositeMode};
///
/// let multiply_over = Composite::new(BlendMode::Multiply, CompositeMode::SourceOver);
/// assert_eq!(Composite::from(BlendMode::Multiply), multiply_over);
/// assert_eq!(Composite::default(), Composite::NORMAL_OVER);
/// ```
///
/// The fields are private so that a future non-separable blend mode or color space can be added
/// without a breaking change; use the accessors and [`Composite::new`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Composite {
    blend: BlendMode,
    op: CompositeMode,
}

impl From<BlendMode> for Composite {
    fn from(blend: BlendMode) -> Self {
        Self::new(blend, CompositeMode::SourceOver)
    }
}

impl From<CompositeMode> for Composite {
    fn from(op: CompositeMode) -> Self {
        Self::new(BlendMode::Normal, op)
    }
}

impl Composite {
    /// Plain source-over compositing with no blending. The default, and by far the common case.
    pub const NORMAL_OVER: Self = Self::new(BlendMode::Normal, CompositeMode::SourceOver);

    /// Pairs a blend mode with a compositing operator.
    #[must_use]
    pub const fn new(blend: BlendMode, op: CompositeMode) -> Self {
        Self { blend, op }
    }

    /// Returns the blend mode.
    #[must_use]
    pub const fn blend(self) -> BlendMode {
        self.blend
    }

    /// Returns the compositing operator.
    #[must_use]
    pub const fn op(self) -> CompositeMode {
        self.op
    }

    /// Composites `src` over `dst`, returning a premultiplied color.
    ///
    /// This is the primitive; [`RgbaBlend::apply`] is this followed by
    /// [`Premultiplied::unpremultiply`]. Prefer this one when the result feeds another
    /// composite, because for integer channels the unpremultiply is lossy.
    ///
    /// Implements the W3C general formula. `Cs`, `Cb`, `as` and `ab` are straight-alpha inputs;
    /// `co` is premultiplied by `ao`:
    ///
    /// ```text
    /// Cs' = (1 - ab) * Cs + ab * B(Cb, Cs)
    /// co  = as * Fa * Cs' + ab * Fb * Cb
    /// ao  = as * Fa + ab * Fb
    /// ```
    ///
    /// ## Accuracy
    ///
    /// For [`Composite::NORMAL_OVER`] with an opaque destination, the `u8` result is exact and
    /// bit-for-bit identical to [`U8x4Rgba::source_over`](crate::rgba::U8x4Rgba::source_over).
    /// Other combinations round at most twice for integer channels and can differ from the
    /// exact rational result by up to 2 LSB.
    #[must_use]
    pub fn composite<C: Channel>(self, src: Rgba<C>, dst: Rgba<C>) -> Premultiplied<Rgba<C>> {
        let (src_a, dst_a) = (src.a, dst.a);
        let Coefficients { src: fa, dst: fb } = self.op.coefficients(src_a, dst_a);

        // Fold `as * Fa` and `ab * Fb` once instead of per channel.
        let weight_src = src_a.scale(fa);
        let weight_dst = dst_a.scale(fb);

        let channel = |cb: C, cs: C| {
            // The blend only applies where the backdrop actually is; elsewhere the source
            // shows through unmixed. That is the `(1 - ab) * Cs + ab * B(Cb, Cs)` term.
            let blended = C::sum_of_products(dst_a.complement(), cs, dst_a, self.blend.mix(cb, cs));
            C::sum_of_products(weight_src, blended, weight_dst, cb)
        };

        Premultiplied::from_premultiplied(Rgba::new(
            channel(dst.r, src.r),
            channel(dst.g, src.g),
            channel(dst.b, src.b),
            C::sum_of_products(src_a, fa, dst_a, fb),
        ))
    }
}

impl<C: Channel> RgbaBlend<C> for Composite {
    fn apply(&self, src: Rgba<C>, dst: Rgba<C>) -> Rgba<C> {
        self.composite(src, dst).unpremultiply()
    }
}

impl<C: Channel> RgbaBlend<C> for CompositeMode {
    /// Composites with [`BlendMode::Normal`].
    fn apply(&self, src: Rgba<C>, dst: Rgba<C>) -> Rgba<C> {
        Composite::new(BlendMode::Normal, *self).apply(src, dst)
    }
}

impl<C: Channel> RgbaBlend<C> for BlendMode {
    /// Blends with [`CompositeMode::SourceOver`].
    fn apply(&self, src: Rgba<C>, dst: Rgba<C>) -> Rgba<C> {
        Composite::new(*self, CompositeMode::SourceOver).apply(src, dst)
    }
}

#[cfg(test)]
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::float_cmp,
    clippy::suboptimal_flops
)]
mod tests {
    use super::*;
    use crate::rgba::{F32x4Rgba, U8x4Rgba};

    fn assert_close(got: F32x4Rgba, want: F32x4Rgba, what: &str) {
        assert!(
            (got.r - want.r).abs() < 1e-5
                && (got.g - want.g).abs() < 1e-5
                && (got.b - want.b).abs() < 1e-5
                && (got.a - want.a).abs() < 1e-5,
            "{what}: got {got}, want {want}",
        );
    }

    #[test]
    fn default_and_conversions() {
        assert_eq!(Composite::default(), Composite::NORMAL_OVER);
        assert_eq!(Composite::NORMAL_OVER.blend(), BlendMode::Normal);
        assert_eq!(Composite::NORMAL_OVER.op(), CompositeMode::SourceOver);
        assert_eq!(
            Composite::from(BlendMode::Multiply),
            Composite::new(BlendMode::Multiply, CompositeMode::SourceOver),
        );
        assert_eq!(
            Composite::from(CompositeMode::Xor),
            Composite::new(BlendMode::Normal, CompositeMode::Xor),
        );
    }

    /// The load-bearing cross-check for retroglyph#547: the generic composite path and the
    /// specialized integer `source_over` must not be able to disagree. Exact, for every
    /// source alpha and a representative spread of colors, against an opaque destination.
    #[test]
    fn u8_normal_over_matches_source_over_exactly() {
        for src_a in 0..=255u8 {
            for s in (0..=255u8).step_by(5) {
                for d in (0..=255u8).step_by(5) {
                    let src = U8x4Rgba::new(s, 255 - s, s, src_a);
                    let dst = U8x4Rgba::new(d, d, 255 - d, 255);
                    assert_eq!(
                        Composite::NORMAL_OVER.apply(src, dst),
                        src.source_over(dst),
                        "src={src} dst={dst}",
                    );
                }
            }
        }
    }

    /// With a translucent destination the generic path is still correct, but it is correct in
    /// *premultiplied* space; comparing straight-alpha output to `source_over` would only
    /// measure the 8-bit unpremultiply, which is unbounded as alpha falls. So compare the
    /// premultiplied result to an `f64` oracle instead.
    #[test]
    fn u8_normal_over_is_correct_for_translucent_dst() {
        let reference = |src: U8x4Rgba, dst: U8x4Rgba| {
            let (sa, da) = (f64::from(src.a) / 255.0, f64::from(dst.a) / 255.0);
            let ch = |s: u8, d: u8| {
                let co = f64::from(s) / 255.0 * sa + f64::from(d) / 255.0 * da * (1.0 - sa);
                (co * 255.0 + 0.5) as u8
            };
            U8x4Rgba::new(
                ch(src.r, dst.r),
                ch(src.g, dst.g),
                ch(src.b, dst.b),
                ((sa + da * (1.0 - sa)) * 255.0 + 0.5) as u8,
            )
        };

        for src_a in (0..=255u8).step_by(3) {
            for dst_a in (0..=255u8).step_by(3) {
                for v in (0..=255u8).step_by(15) {
                    let src = U8x4Rgba::new(v, 200, 30, src_a);
                    let dst = U8x4Rgba::new(10, v, 240, dst_a);
                    let got = Composite::NORMAL_OVER.composite(src, dst).get();
                    let want = reference(src, dst);
                    assert!(
                        got.r.abs_diff(want.r) <= 1
                            && got.g.abs_diff(want.g) <= 1
                            && got.b.abs_diff(want.b) <= 1
                            && got.a.abs_diff(want.a) <= 1,
                        "src={src} dst={dst}: got {got}, want {want}",
                    );
                    assert_eq!(
                        got.a,
                        src.source_over(dst).a,
                        "alpha agrees with the direct path exactly; src={src} dst={dst}",
                    );
                }
            }
        }
    }

    /// Opaque over opaque reduces to the raw mixing function for every blend mode.
    #[test]
    fn opaque_over_opaque_is_the_mix_function() {
        let src = F32x4Rgba::new(0.1, 0.2, 0.3, 1.0);
        let dst = F32x4Rgba::new(0.4, 0.5, 0.6, 1.0);
        for mode in BlendMode::ALL {
            let out = mode.apply(src, dst);
            assert_close(
                out,
                F32x4Rgba::new(
                    mode.mix(dst.r, src.r),
                    mode.mix(dst.g, src.g),
                    mode.mix(dst.b, src.b),
                    1.0,
                ),
                &format!("{mode:?}"),
            );
        }
    }

    /// Compositing onto or from nothing must not invent color.
    #[test]
    fn transparent_inputs() {
        for mode in BlendMode::ALL {
            assert_eq!(
                mode.apply(F32x4Rgba::TRANSPARENT, F32x4Rgba::TRANSPARENT),
                F32x4Rgba::TRANSPARENT,
                "{mode:?}",
            );
            // A transparent source leaves the destination alone under SourceOver.
            assert_close(
                mode.apply(F32x4Rgba::TRANSPARENT, F32x4Rgba::new(0.2, 0.4, 0.6, 1.0)),
                F32x4Rgba::new(0.2, 0.4, 0.6, 1.0),
                &format!("{mode:?} transparent src"),
            );
            // An opaque source over nothing is just the source.
            assert_close(
                mode.apply(F32x4Rgba::new(0.2, 0.4, 0.6, 1.0), F32x4Rgba::TRANSPARENT),
                F32x4Rgba::new(0.2, 0.4, 0.6, 1.0),
                &format!("{mode:?} transparent dst"),
            );
        }
    }

    /// The Porter-Duff operators, with both inputs opaque, reduce to picking one input or
    /// clearing. Transcribed from the operator definitions, not from the implementation.
    #[test]
    fn opaque_porter_duff_table() {
        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 cases: &[(CompositeMode, F32x4Rgba)] = &[
            (CompositeMode::Clear, F32x4Rgba::TRANSPARENT),
            (CompositeMode::Source, src),
            (CompositeMode::Destination, dst),
            (CompositeMode::SourceOver, src),
            (CompositeMode::DestinationOver, dst),
            (CompositeMode::SourceIn, src),
            (CompositeMode::DestinationIn, dst),
            (CompositeMode::SourceOut, F32x4Rgba::TRANSPARENT),
            (CompositeMode::DestinationOut, F32x4Rgba::TRANSPARENT),
            (CompositeMode::SourceAtop, src),
            (CompositeMode::DestinationAtop, dst),
            (CompositeMode::Xor, F32x4Rgba::TRANSPARENT),
            (CompositeMode::Plus, F32x4Rgba::new(0.5, 0.7, 0.9, 1.0)),
        ];
        assert_eq!(cases.len(), CompositeMode::ALL.len(), "table is complete");
        for &(mode, want) in cases {
            assert_close(mode.apply(src, dst), want, &format!("{mode:?}"));
        }
    }

    /// `Plus` used to return `a = 2.0` and require a manual clamp.
    #[test]
    fn plus_saturates_instead_of_overflowing() {
        let out = CompositeMode::Plus.apply(
            F32x4Rgba::new(0.8, 0.8, 0.8, 1.0),
            F32x4Rgba::new(0.8, 0.8, 0.8, 1.0),
        );
        assert_eq!(out.a, 1.0);
        assert!(out.r <= 1.0);
        assert_eq!(out, out.clamp(), "already in range");
    }

    /// The alpha bug fixed in 0.2.1 for the `u8` path, now also fixed for `f32`: source-over
    /// alpha is `as + ab * (1 - as)`, not `as * as + ab * (1 - as)`.
    #[test]
    fn source_over_alpha_is_correct_for_f32() {
        let src = F32x4Rgba::new(1.0, 0.0, 0.0, 0.5);
        let dst = F32x4Rgba::new(0.0, 0.0, 1.0, 1.0);
        let out = CompositeMode::SourceOver.apply(src, dst);
        assert_close(out, F32x4Rgba::new(0.5, 0.0, 0.5, 1.0), "src over");
    }

    /// Blending is only visible where the backdrop is; a partially transparent backdrop
    /// interpolates between the blended and the raw source.
    #[test]
    fn blend_is_weighted_by_backdrop_alpha() {
        let src = F32x4Rgba::new(0.5, 0.5, 0.5, 1.0);
        // Multiply against a half-transparent black backdrop: half blended (0.0), half raw
        // source (0.5), then composited over.
        let dst = F32x4Rgba::new(0.0, 0.0, 0.0, 0.5);
        let out = Composite::new(BlendMode::Multiply, CompositeMode::SourceOver).apply(src, dst);
        assert_close(out, F32x4Rgba::new(0.25, 0.25, 0.25, 1.0), "multiply");
    }

    /// `Normal` composited with each operator must equal that operator used on its own.
    #[test]
    fn normal_blend_is_the_identity_for_every_operator() {
        let src = F32x4Rgba::new(0.1, 0.7, 0.3, 0.4);
        let dst = F32x4Rgba::new(0.8, 0.2, 0.6, 0.9);
        for op in CompositeMode::ALL {
            assert_eq!(
                Composite::new(BlendMode::Normal, op).apply(src, dst),
                op.apply(src, dst),
                "{op:?}",
            );
        }
    }

    /// `SourceOver` composited with each blend mode must equal that blend mode on its own.
    #[test]
    fn source_over_is_the_identity_for_every_blend_mode() {
        let src = F32x4Rgba::new(0.1, 0.7, 0.3, 0.4);
        let dst = F32x4Rgba::new(0.8, 0.2, 0.6, 0.9);
        for blend in BlendMode::ALL {
            assert_eq!(
                Composite::new(blend, CompositeMode::SourceOver).apply(src, dst),
                blend.apply(src, dst),
                "{blend:?}",
            );
        }
    }

    /// Integer and float compositing must describe the same operation.
    #[test]
    fn u8_and_f32_composites_agree() {
        let src = U8x4Rgba::new(26, 179, 77, 102);
        let dst = U8x4Rgba::new(204, 51, 153, 230);
        for blend in BlendMode::ALL {
            for op in CompositeMode::ALL {
                let composite = Composite::new(blend, op);
                // Compare *premultiplied* results. This is the math under test; `apply` adds a
                // lossy unpremultiply on top, which at low alpha amplifies a sub-LSB
                // difference into several LSB and would only measure that division.
                let int = composite.composite(src, dst).get();
                let flt: F32x4Rgba = composite
                    .composite(F32x4Rgba::from(src), F32x4Rgba::from(dst))
                    .get();
                let flt = U8x4Rgba::from(flt);
                assert!(
                    int.r.abs_diff(flt.r) <= 2
                        && int.g.abs_diff(flt.g) <= 2
                        && int.b.abs_diff(flt.b) <= 2
                        && int.a.abs_diff(flt.a) <= 1,
                    "{blend:?} + {op:?}: u8 {int}, f32 {flt}",
                );
            }
        }
    }

    /// The straight-alpha `u8` path additionally carries the unpremultiply error, which grows
    /// without bound as alpha falls. Pinned so the `Premultiplied` docs stay honest.
    #[test]
    fn u8_unpremultiply_error_is_the_dominant_term_at_low_alpha() {
        let src = U8x4Rgba::new(26, 179, 77, 8);
        let dst = U8x4Rgba::new(204, 51, 153, 8);
        let composite = Composite::new(BlendMode::Multiply, CompositeMode::SourceOut);
        let premultiplied = composite.composite(src, dst).get();
        let straight = composite.apply(src, dst);
        assert!(
            straight.r.abs_diff(premultiplied.r) > 2,
            "unpremultiply at alpha {} should be visible",
            straight.a,
        );
    }

    /// `composite` returns premultiplied color; `apply` is that plus an unpremultiply.
    #[test]
    fn composite_returns_premultiplied() {
        let src = F32x4Rgba::new(1.0, 1.0, 1.0, 0.5);
        let dst = F32x4Rgba::TRANSPARENT;
        let premultiplied = Composite::NORMAL_OVER.composite(src, dst);
        assert_close(
            premultiplied.get(),
            F32x4Rgba::new(0.5, 0.5, 0.5, 0.5),
            "premul",
        );
        assert_close(
            Composite::NORMAL_OVER.apply(src, dst),
            F32x4Rgba::new(1.0, 1.0, 1.0, 0.5),
            "straight",
        );
    }

    #[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;
        BlendMode::Overlay.apply_slice(&src, &mut batch);
        for (i, (s, d)) in src.iter().zip(dst.iter()).enumerate() {
            assert_eq!(batch[i], BlendMode::Overlay.apply(*s, *d));
        }
    }

    #[test]
    fn apply_slice_works_for_u8() {
        let src = [U8x4Rgba::new(255, 0, 0, 128), U8x4Rgba::WHITE];
        let dst = [U8x4Rgba::BLACK; 2];
        let mut batch = dst;
        CompositeMode::SourceOver.apply_slice(&src, &mut batch);
        assert_eq!(batch[0], src[0].source_over(dst[0]));
        assert_eq!(batch[1], U8x4Rgba::WHITE);
    }

    #[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::WHITE; 2];
        CompositeMode::SourceOver.apply_slice(&src, &mut dst);
    }

    #[test]
    fn composite_hash() {
        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(Composite::NORMAL_OVER);
        set.insert(Composite::default());
        assert_eq!(set.len(), 1);
        set.insert(Composite::from(BlendMode::Multiply));
        assert_eq!(set.len(), 2);
    }
}