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
use std::ops::{Add, Deref, DerefMut, Div, Mul, Sub};
use approx::ApproxEq;
use num_traits::Float;

use {clamp, Alpha, Blend, ComponentWise, Mix, Pixel};
use encoding::pixel::RawPixel;

///Premultiplied alpha wrapper.
///
///Premultiplied colors are commonly used in composition algorithms to
///simplify the calculations. It may also be preferred when interpolating
///between colors, which is one of the reasons why it's offered as a separate
///type. The other reason is to make it easier to avoid unnecessary
///computations in composition chains.
///
///```
///use palette::{Blend, LinSrgb, LinSrgba};
///use palette::blend::PreAlpha;
///
///let a = PreAlpha::from(LinSrgba::new(0.4, 0.5, 0.5, 0.3));
///let b = PreAlpha::from(LinSrgba::new(0.3, 0.8, 0.4, 0.4));
///let c = PreAlpha::from(LinSrgba::new(0.7, 0.1, 0.8, 0.8));
///
///let res = LinSrgb::from_premultiplied(a.screen(b).overlay(c));
///```
///
///Note that converting to and from premultiplied alpha will cause the alpha
///component to be clamped to [0.0, 1.0].
#[derive(Clone, Copy, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[repr(C)]
pub struct PreAlpha<C, T: Float> {
    ///The premultiplied color components (`original.color * original.alpha`).
    #[cfg_attr(feature = "serde", serde(flatten))]
    pub color: C,

    ///The transparency component. 0.0 is fully transparent and 1.0 is fully
    ///opaque.
    pub alpha: T,
}

impl<C, T> From<Alpha<C, T>> for PreAlpha<C, T>
where
    C: ComponentWise<Scalar = T>,
    T: Float,
{
    fn from(color: Alpha<C, T>) -> PreAlpha<C, T> {
        let alpha = clamp(color.alpha, T::zero(), T::one());

        PreAlpha {
            color: color.color.component_wise_self(|a| a * alpha),
            alpha: alpha,
        }
    }
}

impl<C, T> From<PreAlpha<C, T>> for Alpha<C, T>
where
    C: ComponentWise<Scalar = T>,
    T: Float,
{
    fn from(color: PreAlpha<C, T>) -> Alpha<C, T> {
        let alpha = clamp(color.alpha, T::zero(), T::one());

        let color = color.color.component_wise_self(|a| {
            if alpha.is_normal() {
                a / alpha
            } else {
                T::zero()
            }
        });

        Alpha {
            color: color,
            alpha: alpha,
        }
    }
}

impl<C, T> Blend for PreAlpha<C, T>
where
    C: Blend<Color = C> + ComponentWise<Scalar = T>,
    T: Float,
{
    type Color = C;

    fn into_premultiplied(self) -> PreAlpha<C, T> {
        self
    }

    fn from_premultiplied(color: PreAlpha<C, T>) -> PreAlpha<C, T> {
        color
    }
}

impl<C: Mix> Mix for PreAlpha<C, C::Scalar> {
    type Scalar = C::Scalar;

    fn mix(&self, other: &PreAlpha<C, C::Scalar>, factor: C::Scalar) -> PreAlpha<C, C::Scalar> {
        PreAlpha {
            color: self.color.mix(&other.color, factor),
            alpha: self.alpha + factor * (other.alpha - self.alpha),
        }
    }
}

impl<C: ComponentWise<Scalar = T>, T: Float> ComponentWise for PreAlpha<C, T> {
    type Scalar = T;

    fn component_wise<F: FnMut(T, T) -> T>(
        &self,
        other: &PreAlpha<C, T>,
        mut f: F,
    ) -> PreAlpha<C, T> {
        PreAlpha {
            alpha: f(self.alpha, other.alpha),
            color: self.color.component_wise(&other.color, f),
        }
    }

    fn component_wise_self<F: FnMut(T) -> T>(&self, mut f: F) -> PreAlpha<C, T> {
        PreAlpha {
            alpha: f(self.alpha),
            color: self.color.component_wise_self(f),
        }
    }
}

unsafe impl<T: Float, C: Pixel<T>> Pixel<T> for PreAlpha<C, T> {
    const CHANNELS: usize = C::CHANNELS + 1;
}

impl<C: Default, T: Float> Default for PreAlpha<C, T> {
    fn default() -> PreAlpha<C, T> {
        PreAlpha {
            color: C::default(),
            alpha: T::one(),
        }
    }
}

impl<C, T> ApproxEq for PreAlpha<C, T>
where
    C: ApproxEq<Epsilon = T::Epsilon>,
    T: ApproxEq + Float,
    T::Epsilon: Copy,
{
    type Epsilon = T::Epsilon;

    fn default_epsilon() -> Self::Epsilon {
        T::default_epsilon()
    }

    fn default_max_relative() -> Self::Epsilon {
        T::default_max_relative()
    }

    fn default_max_ulps() -> u32 {
        T::default_max_ulps()
    }

    fn relative_eq(
        &self,
        other: &PreAlpha<C, T>,
        epsilon: Self::Epsilon,
        max_relative: Self::Epsilon,
    ) -> bool {
        self.color.relative_eq(&other.color, epsilon, max_relative)
            && self.alpha.relative_eq(&other.alpha, epsilon, max_relative)
    }

    fn ulps_eq(&self, other: &PreAlpha<C, T>, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
        self.color.ulps_eq(&other.color, epsilon, max_ulps)
            && self.alpha.ulps_eq(&other.alpha, epsilon, max_ulps)
    }
}

impl<C: Add, T: Float> Add for PreAlpha<C, T> {
    type Output = PreAlpha<C::Output, T>;

    fn add(self, other: PreAlpha<C, T>) -> PreAlpha<C::Output, T> {
        PreAlpha {
            color: self.color + other.color,
            alpha: self.alpha + other.alpha,
        }
    }
}

impl<T: Float, C: Add<T>> Add<T> for PreAlpha<C, T> {
    type Output = PreAlpha<C::Output, T>;

    fn add(self, c: T) -> PreAlpha<C::Output, T> {
        PreAlpha {
            color: self.color + c,
            alpha: self.alpha + c,
        }
    }
}

impl<C: Sub, T: Float> Sub for PreAlpha<C, T> {
    type Output = PreAlpha<C::Output, T>;

    fn sub(self, other: PreAlpha<C, T>) -> PreAlpha<C::Output, T> {
        PreAlpha {
            color: self.color - other.color,
            alpha: self.alpha - other.alpha,
        }
    }
}

impl<T: Float, C: Sub<T>> Sub<T> for PreAlpha<C, T> {
    type Output = PreAlpha<C::Output, T>;

    fn sub(self, c: T) -> PreAlpha<C::Output, T> {
        PreAlpha {
            color: self.color - c,
            alpha: self.alpha - c,
        }
    }
}

impl<C: Mul, T: Float> Mul for PreAlpha<C, T> {
    type Output = PreAlpha<C::Output, T>;

    fn mul(self, other: PreAlpha<C, T>) -> PreAlpha<C::Output, T> {
        PreAlpha {
            color: self.color * other.color,
            alpha: self.alpha * other.alpha,
        }
    }
}

impl<T: Float, C: Mul<T>> Mul<T> for PreAlpha<C, T> {
    type Output = PreAlpha<C::Output, T>;

    fn mul(self, c: T) -> PreAlpha<C::Output, T> {
        PreAlpha {
            color: self.color * c,
            alpha: self.alpha * c,
        }
    }
}

impl<C: Div, T: Float> Div for PreAlpha<C, T> {
    type Output = PreAlpha<C::Output, T>;

    fn div(self, other: PreAlpha<C, T>) -> PreAlpha<C::Output, T> {
        PreAlpha {
            color: self.color / other.color,
            alpha: self.alpha / other.alpha,
        }
    }
}

impl<T: Float, C: Div<T>> Div<T> for PreAlpha<C, T> {
    type Output = PreAlpha<C::Output, T>;

    fn div(self, c: T) -> PreAlpha<C::Output, T> {
        PreAlpha {
            color: self.color / c,
            alpha: self.alpha / c,
        }
    }
}

impl<C, T, P> AsRef<P> for PreAlpha<C, T>
where
    C: Pixel<T>,
    T: Float,
    P: RawPixel<T> + ?Sized,
{
    fn as_ref(&self) -> &P {
        self.as_raw()
    }
}

impl<C, T, P> AsMut<P> for PreAlpha<C, T>
where
    C: Pixel<T>,
    T: Float,
    P: RawPixel<T> + ?Sized,
{
    fn as_mut(&mut self) -> &mut P {
        self.as_raw_mut()
    }
}

impl<C, T: Float> Deref for PreAlpha<C, T> {
    type Target = C;

    fn deref(&self) -> &C {
        &self.color
    }
}

impl<C, T: Float> DerefMut for PreAlpha<C, T> {
    fn deref_mut(&mut self) -> &mut C {
        &mut self.color
    }
}

#[cfg(test)]
#[cfg(feature = "serde")]
mod test {
    use super::PreAlpha;
    use rgb::Rgb;
    use encoding::Srgb;

    #[cfg(feature = "serde")]
    #[test]
    fn serialize() {
        let color = PreAlpha {
            color: Rgb::<Srgb>::new(0.3, 0.8, 0.1),
            alpha: 0.5
        };

        let serialized = ::serde_json::to_string(&color).unwrap();

        assert_eq!(serialized, r#"{"red":0.3,"green":0.8,"blue":0.1,"alpha":0.5}"#);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn deserialize() {
        let expected = PreAlpha {
            color: Rgb::<Srgb>::new(0.3, 0.8, 0.1),
            alpha: 0.5
        };

        let deserialized: PreAlpha<_, _> = ::serde_json::from_str(r#"{"red":0.3,"green":0.8,"blue":0.1,"alpha":0.5}"#).unwrap();

        assert_eq!(deserialized, expected);
    }
}