Skip to main content

xrack_layout/
image.rs

1use crate::{Rect, Size};
2use xrack_runtime::{
3    ImageFit, ImageHorizontalAlignment as Horizontal, ImageRendering, ImageTileMode,
4    ImageVerticalAlignment as Vertical, NineSlice, Node, Value,
5};
6
7/// The visible part of an image in integer source pixels.
8#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
9pub struct ImageRegion {
10    pub x: u32,
11    pub y: u32,
12    pub width: u32,
13    pub height: u32,
14}
15
16impl ImageRegion {
17    pub fn full([width, height]: [u32; 2]) -> Self {
18        Self {
19            x: 0,
20            y: 0,
21            width,
22            height,
23        }
24    }
25
26    pub fn for_node(node: &Node, size: [u32; 2]) -> Self {
27        fn axis(start: Option<i64>, extent: Option<i64>, limit: u32) -> (u32, u32) {
28            let start = start.unwrap_or(0);
29            let limit = i64::from(limit);
30            let end = extent.map_or(limit, |extent| start.saturating_add(extent.max(0)));
31            let start = start.clamp(0, limit);
32            (start as u32, (end.clamp(start, limit) - start) as u32)
33        }
34        let (x, width) = axis(
35            node.int("source-clip-x"),
36            node.int("source-clip-width"),
37            size[0],
38        );
39        let (y, height) = axis(
40            node.int("source-clip-y"),
41            node.int("source-clip-height"),
42            size[1],
43        );
44        Self {
45            x,
46            y,
47            width,
48            height,
49        }
50    }
51
52    pub fn size(self) -> [u32; 2] {
53        [self.width, self.height]
54    }
55
56    pub fn logical_size(self) -> Size {
57        Size::new(self.width as f32, self.height as f32)
58    }
59
60    /// Preserve edge bands that survive the clip. If an axis shows only one
61    /// border band, that band becomes the flexible region on that axis.
62    pub fn clipped_edges(self, [width, height]: [u32; 2], edges: NineSlice) -> NineSlice {
63        fn axis(start: u32, extent: u32, limit: u32, before: u32, after: u32) -> [u32; 2] {
64            let first = before.saturating_sub(start).min(extent);
65            let last = start
66                .saturating_add(extent)
67                .saturating_sub(limit.saturating_sub(after))
68                .min(extent);
69            if first.saturating_add(last) >= extent {
70                [0, 0]
71            } else {
72                [first, last]
73            }
74        }
75        let [left, right] = axis(self.x, self.width, width, edges.left, edges.right);
76        let [top, bottom] = axis(self.y, self.height, height, edges.top, edges.bottom);
77        NineSlice {
78            left,
79            right,
80            top,
81            bottom,
82        }
83    }
84}
85
86/// Presentation options shared by atlas regions, animations and full images.
87#[derive(Clone, Copy)]
88pub struct ImagePresentation {
89    pub region: ImageRegion,
90    pub modes: [ImageTileMode; 2],
91    pub rendering: ImageRendering,
92    fit: ImageFit,
93    alignment: [f32; 2],
94}
95
96impl ImagePresentation {
97    pub fn whole(size: [u32; 2], fit: ImageFit) -> Self {
98        Self {
99            region: ImageRegion::full(size),
100            modes: [ImageTileMode::Stretch; 2],
101            rendering: ImageRendering::Smooth,
102            fit,
103            alignment: [0.5; 2],
104        }
105    }
106
107    pub fn for_node(node: &Node, size: [u32; 2], in_layout: bool) -> Self {
108        let x = match node.properties.get("horizontal-alignment") {
109            Some(Value::ImageHorizontalAlignment(Horizontal::Left)) => 0.0,
110            Some(Value::ImageHorizontalAlignment(Horizontal::Right)) => 1.0,
111            _ => 0.5,
112        };
113        let y = match node.properties.get("vertical-alignment") {
114            Some(Value::ImageVerticalAlignment(Vertical::Top)) => 0.0,
115            Some(Value::ImageVerticalAlignment(Vertical::Bottom)) => 1.0,
116            _ => 0.5,
117        };
118        let rendering = match node.properties.get("image-rendering") {
119            Some(Value::ImageRendering(rendering)) => *rendering,
120            _ => ImageRendering::Smooth,
121        };
122        Self {
123            region: ImageRegion::for_node(node, size),
124            modes: [
125                node.image_tile_mode("horizontal-tile-mode"),
126                node.image_tile_mode("vertical-tile-mode"),
127            ],
128            rendering,
129            fit: node.image_fit("image-fit").unwrap_or(
130                if in_layout || node.kind == "MediaPlayer" {
131                    ImageFit::Contain
132                } else {
133                    ImageFit::Fill
134                },
135            ),
136            alignment: [x, y],
137        }
138    }
139
140    pub fn placement(self, bounds: Rect) -> ImagePlacement {
141        let source = self.region.logical_size();
142        let mut pattern = fitted_rect(bounds, source, self.fit, self.alignment);
143        let repeat = self.modes.map(|mode| mode != ImageTileMode::Stretch);
144        let mut visible = pattern.intersect(bounds);
145        if repeat[0] {
146            pattern.x = bounds.x;
147            pattern.width = tile_extent(bounds.width, source.width, self.modes[0]);
148            visible.x = bounds.x;
149            visible.width = bounds.width;
150        }
151        if repeat[1] {
152            pattern.y = bounds.y;
153            pattern.height = tile_extent(bounds.height, source.height, self.modes[1]);
154            visible.y = bounds.y;
155            visible.height = bounds.height;
156        }
157        ImagePlacement {
158            pattern,
159            visible,
160            repeat,
161        }
162    }
163}
164
165pub struct ImagePlacement {
166    pub pattern: Rect,
167    pub visible: Rect,
168    pub repeat: [bool; 2],
169}
170
171pub fn tile_extent(available: f32, natural: f32, mode: ImageTileMode) -> f32 {
172    match mode {
173        ImageTileMode::Stretch => available,
174        ImageTileMode::Repeat => natural,
175        ImageTileMode::Round => available / (available / natural).ceil().max(1.0),
176    }
177}
178
179pub fn fitted_rect(bounds: Rect, source: Size, fit: ImageFit, align: [f32; 2]) -> Rect {
180    let (width, height) = match fit {
181        ImageFit::Fill => return bounds,
182        ImageFit::Preserve => (source.width, source.height),
183        ImageFit::Contain | ImageFit::Cover => {
184            let x = bounds.width / source.width;
185            let y = bounds.height / source.height;
186            let scale = if fit == ImageFit::Contain {
187                x.min(y)
188            } else {
189                x.max(y)
190            };
191            (source.width * scale, source.height * scale)
192        }
193    };
194    Rect::new(
195        bounds.x + (bounds.width - width) * align[0],
196        bounds.y + (bounds.height - height) * align[1],
197        width,
198        height,
199    )
200}