Skip to main content

cranpose_render_common/
style_shared.rs

1use std::{ops::Range, rc::Rc};
2
3use cranpose_ui::{Brush, DrawCommand};
4use cranpose_ui_graphics::{
5    Color, ColorFilter, CommandRecording, CornerRadii, DrawPlacement, DrawPrimitive, GraphicsLayer,
6    Size,
7};
8
9pub use crate::graph::quad_bounds;
10use crate::layer_transform::{layer_scale_x, layer_scale_y, layer_uniform_scale};
11
12/// The colour a primitive is actually painted in, once this layer has had its
13/// say.
14///
15/// The colour is snapped to eight bits *first*, because that is where the
16/// platform's own colour type already is by the time anything paints with it
17/// (see [`Color::srgb_8bit`]). Only then does the layer's alpha multiply it.
18/// The order is the whole point: an isolated layer's contents land in an 8-bit
19/// buffer and the alpha multiplies whole channel values, so
20/// `round(round(c * 255) * a)` and not `round(c * 255 * a)`.
21pub fn apply_layer_to_color(color: Color, layer: &GraphicsLayer) -> Color {
22    apply_paint_to_color(color, layer.alpha, layer.color_filter.as_ref())
23}
24
25/// The colour a primitive is painted in under a layer's `alpha` and
26/// `color_filter`, the only parts of a layer a colour takes; see
27/// [`apply_layer_to_color`].
28pub fn apply_paint_to_color(color: Color, alpha: f32, color_filter: Option<&ColorFilter>) -> Color {
29    let color = color.srgb_8bit();
30    let color = Color(color.0, color.1, color.2, (color.3 * alpha).clamp(0.0, 1.0));
31    match color_filter {
32        Some(filter) => {
33            let [r, g, b, a] = filter.apply_rgba([color.0, color.1, color.2, color.3]);
34            Color(r, g, b, a)
35        }
36        None => color,
37    }
38}
39
40/// Combines two optional color filters into one. With only one present, that filter is returned.
41pub fn compose_color_filters(
42    base: Option<&ColorFilter>,
43    overlay: Option<&ColorFilter>,
44) -> Option<ColorFilter> {
45    match (base, overlay) {
46        (None, None) => None,
47        (Some(filter), None) | (None, Some(filter)) => Some(filter.clone()),
48        (Some(filter), Some(next)) => Some(filter.compose(next)),
49    }
50}
51
52/// Resolves `brush` against `layer`: its colors take the layer's alpha and color filter, and a
53/// gradient's geometry takes the layer's scale.
54pub fn apply_layer_to_brush(brush: Brush, layer: &GraphicsLayer) -> Brush {
55    if layer.alpha == 1.0
56        && layer.color_filter.is_none()
57        && layer_scale_x(layer) == 1.0
58        && layer_scale_y(layer) == 1.0
59    {
60        return brush.map_colors(Color::srgb_8bit);
61    }
62    scale_brush_geometry(brush, layer).map_colors(|color| apply_layer_to_color(color, layer))
63}
64
65/// Resolves `brush` against the scale of `layer` and snaps its colors to eight bits. The layer's
66/// alpha and color filter stay off: a [`LayerPaint`](crate::layer_paint::LayerPaint) applies them
67/// where the colors resolve. [`apply_layer_to_brush`] gives this brush with them applied.
68pub fn apply_layer_geometry_to_brush(brush: Brush, layer: &GraphicsLayer) -> Brush {
69    scale_brush_geometry(brush, layer).map_colors(Color::srgb_8bit)
70}
71
72fn scale_brush_geometry(brush: Brush, layer: &GraphicsLayer) -> Brush {
73    let scale_x = layer_scale_x(layer);
74    let scale_y = layer_scale_y(layer);
75    let uniform_scale = layer_uniform_scale(layer);
76
77    match brush {
78        Brush::Solid(color) => Brush::Solid(color),
79        Brush::LinearGradient {
80            colors,
81            stops,
82            mut start,
83            mut end,
84            tile_mode,
85        } => {
86            start.x *= scale_x;
87            start.y *= scale_y;
88            end.x *= scale_x;
89            end.y *= scale_y;
90            Brush::LinearGradient {
91                colors,
92                stops,
93                start,
94                end,
95                tile_mode,
96            }
97        }
98        Brush::RadialGradient {
99            colors,
100            stops,
101            mut center,
102            mut radius,
103            tile_mode,
104        } => {
105            center.x *= scale_x;
106            center.y *= scale_y;
107            radius *= uniform_scale;
108            Brush::RadialGradient {
109                colors,
110                stops,
111                center,
112                radius,
113                tile_mode,
114            }
115        }
116        Brush::SweepGradient {
117            colors,
118            stops,
119            mut center,
120        } => {
121            center.x *= scale_x;
122            center.y *= scale_y;
123            Brush::SweepGradient {
124                colors,
125                stops,
126                center,
127            }
128        }
129    }
130}
131
132/// A layer-resolved brush, split at the solid/gradient boundary.
133///
134/// The per-frame shape emit produces one of these for every draw: the solid
135/// case — effectively all of a heavy animated scene — carries its color
136/// inline, so emitting a shape neither clones a `Brush` nor leaves an enum
137/// with heap-carrying variants for frame teardown to walk. Only the rare
138/// gradient still travels as a cloned [`Brush`].
139#[derive(Clone, Debug, PartialEq)]
140pub enum ResolvedBrush {
141    /// A solid color, already layer-resolved.
142    Solid(Color),
143    /// A non-solid brush (gradients), already layer-resolved.
144    Other(Brush),
145}
146
147impl ResolvedBrush {
148    /// Wraps `brush` as `Solid` when it is a solid color and as `Other` otherwise.
149    pub fn from_brush(brush: Brush) -> Self {
150        match brush {
151            Brush::Solid(color) => Self::Solid(color),
152            other => Self::Other(other),
153        }
154    }
155
156    /// The plain `Brush` this resolved form stands for — same values,
157    /// reassembled for consumers that keep speaking `Brush`.
158    pub fn into_brush(self) -> Brush {
159        match self {
160            Self::Solid(color) => Brush::Solid(color),
161            Self::Other(brush) => brush,
162        }
163    }
164}
165
166/// [`apply_layer_to_brush`] without the solid-brush clone: the borrowed
167/// brush's color is copied (or layer-adjusted) inline, and only gradients
168/// are cloned. Produces exactly the values `apply_layer_to_brush` would —
169/// both branches below mirror its fast path and its `Solid` arm verbatim.
170pub fn resolve_layer_brush(brush: &Brush, layer: &GraphicsLayer) -> ResolvedBrush {
171    match brush {
172        Brush::Solid(color) => {
173            if layer.alpha == 1.0
174                && layer.color_filter.is_none()
175                && layer_scale_x(layer) == 1.0
176                && layer_scale_y(layer) == 1.0
177            {
178                ResolvedBrush::Solid(*color)
179            } else {
180                ResolvedBrush::Solid(apply_layer_to_color(*color, layer))
181            }
182        }
183        other => ResolvedBrush::Other(apply_layer_to_brush(other.clone(), layer)),
184    }
185}
186
187/// Multiplies every corner radius by `scale`.
188pub fn scale_corner_radii(radii: CornerRadii, scale: f32) -> CornerRadii {
189    CornerRadii {
190        top_left: radii.top_left * scale,
191        top_right: radii.top_right * scale,
192        bottom_right: radii.bottom_right * scale,
193        bottom_left: radii.bottom_left * scale,
194    }
195}
196
197/// Records `command` at `size` and returns the primitives that `placement` draws, or an empty
198/// list when the command has no part for that placement.
199pub fn primitives_for_placement(
200    command: &DrawCommand,
201    placement: DrawPlacement,
202    size: Size,
203) -> Vec<DrawPrimitive> {
204    let Some(split) = placement_split(command, placement) else {
205        return Vec::new();
206    };
207    let mut recording = CommandRecording::default();
208    let segments = record_with(command, split, size, &mut recording);
209    recording.primitives(segments).collect()
210}
211
212/// Records `command` into the recording `storage` gives, one the caller
213/// kept from an earlier frame so its buffers keep the capacity they earned,
214/// and names the segments `placement` draws: everything for a behind or
215/// overlay command, the part before or after the last content marker for a
216/// with-content command. `None` when the command has no `placement` half,
217/// in which case storage is not acquired and nothing is recorded. The
218/// recording is drawn in place: only one another handle still shares is
219/// copied first.
220pub fn recording_for_placement_reusing(
221    command: &DrawCommand,
222    placement: DrawPlacement,
223    size: Size,
224    storage: impl FnOnce() -> Rc<CommandRecording>,
225) -> Option<(Rc<CommandRecording>, Range<u32>)> {
226    let split = placement_split(command, placement)?;
227    let mut shared = storage();
228    let segments = record_with(command, split, size, Rc::make_mut(&mut shared));
229    Some((shared, segments))
230}
231
232// Records `command` anew into `recording`, which no other handle holds,
233// and names the segments `placement` draws; `None` when the command has no
234// `placement` half.
235pub(crate) fn record_in_place(
236    command: &DrawCommand,
237    placement: DrawPlacement,
238    size: Size,
239    recording: &mut CommandRecording,
240) -> Option<Range<u32>> {
241    let split = placement_split(command, placement)?;
242    Some(record_with(command, split, size, recording))
243}
244
245// Whether `command` draws anything in `placement`.
246pub(crate) fn draws_in(command: &DrawCommand, placement: DrawPlacement) -> bool {
247    placement_split(command, placement).is_some()
248}
249
250// Whether `command` draws in `placement`, and for a with-content command
251// the half of it `placement` takes.
252fn placement_split(
253    command: &DrawCommand,
254    placement: DrawPlacement,
255) -> Option<Option<DrawPlacement>> {
256    match (placement, command) {
257        (DrawPlacement::Behind, DrawCommand::Behind(_) | DrawCommand::Background(_))
258        | (DrawPlacement::Overlay, DrawCommand::Overlay(_)) => Some(None),
259        (_, DrawCommand::WithContent(_)) => Some(Some(placement)),
260        _ => None,
261    }
262}
263
264fn record_with(
265    command: &DrawCommand,
266    split: Option<DrawPlacement>,
267    size: Size,
268    recording: &mut CommandRecording,
269) -> Range<u32> {
270    let mut scope = cranpose_ui::command_draw_scope(size, recording);
271    command.draw(&mut scope);
272    scope.finish();
273    match split {
274        None => recording.all_segments(),
275        Some(placement) => recording.content_split(placement),
276    }
277}
278
279#[cfg(test)]
280#[path = "tests/style_shared_tests.rs"]
281mod tests;