Skip to main content

cranpose_render_common/
layer_paint.rs

1//! The alpha and color filter that a layer drawn in place lays over the
2//! colors of its content.
3
4use std::hash::{Hash, Hasher};
5
6use cranpose_ui::Brush;
7use cranpose_ui_graphics::{Color, ColorFilter, GraphicsLayer, RenderHash};
8
9use crate::style_shared::apply_paint_to_color;
10
11/// The alpha and color filter of a layer drawn in place. Every color of the
12/// layer's content takes them, as [`apply_layer_to_color`] applies them. A
13/// text resolves the colors of its glyphs from its style and spans first.
14/// Each resolved color then takes this paint.
15///
16/// [`apply_layer_to_color`]: crate::style_shared::apply_layer_to_color
17#[derive(Clone, Debug, PartialEq)]
18pub struct LayerPaint {
19    alpha: f32,
20    color_filter: Option<ColorFilter>,
21}
22
23impl LayerPaint {
24    /// The paint that leaves every color as it is.
25    pub const NONE: Self = Self {
26        alpha: 1.0,
27        color_filter: None,
28    };
29
30    /// The alpha and color filter of `layer`.
31    pub fn of(layer: &GraphicsLayer) -> Self {
32        Self {
33            alpha: layer.alpha,
34            color_filter: layer.color_filter.clone(),
35        }
36    }
37
38    // Whether the paint changes a color.
39    pub(crate) fn paints(&self) -> bool {
40        self.alpha != 1.0 || self.color_filter.is_some()
41    }
42
43    // `color` under the paint: snapped to eight bits, then multiplied by the
44    // alpha and filtered. A paint that changes nothing leaves `color` as it
45    // is.
46    pub(crate) fn color(&self, color: Color) -> Color {
47        if self.paints() {
48            apply_paint_to_color(color, self.alpha, self.color_filter.as_ref())
49        } else {
50            color
51        }
52    }
53
54    /// `brush` with each of its colors under the paint.
55    pub fn brush(&self, brush: Brush) -> Brush {
56        if self.paints() {
57            brush.map_colors(|color| self.color(color))
58        } else {
59            brush
60        }
61    }
62}
63
64impl Hash for LayerPaint {
65    fn hash<H: Hasher>(&self, state: &mut H) {
66        state.write_u32(self.alpha.to_bits());
67        state.write_u64(
68            self.color_filter
69                .as_ref()
70                .map_or(0, RenderHash::render_hash),
71        );
72    }
73}