Skip to main content

ssplayer_wgpu/
fit.rs

1//! `fit` / `align` — placing an animation inside a box the host laid out.
2//!
3//! The player draws at authored scale into whatever target it is given, which is
4//! what a game wants and what a UI host cannot use: a UI host has a box and needs
5//! the art fitted into it. The vocabulary here is the family's — `contain` /
6//! `cover` / `none` and nine alignments, the words `<Image resizeMode>` already
7//! taught every host — so this is a port of a settled contract rather than a new
8//! design.
9//!
10//! Everything in this module is arithmetic over a box and a target size. There is
11//! no GPU work in it and no state, which is why it lives in the player where the
12//! C ABI and every adapter inherit it, rather than in one host's adapter crate.
13
14/// How the content box is scaled into the view.
15#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
16pub enum Fit {
17    /// Scale until the box fits entirely inside the view: `min(sx, sy)`.
18    #[default]
19    Contain,
20    /// Scale until the box covers the view: `max(sx, sy)`. The overflow is not
21    /// clipped — the player has no scissor of its own, so a host that needs the
22    /// spill hidden supplies one.
23    Cover,
24    /// No fit at all: scale 1, origin at the view's centre. The placement is then
25    /// the caller's own [`Placement::scale`] and [`Placement::offset`].
26    None,
27}
28
29/// Which point of the content box lands on the matching point of the view.
30///
31/// It decomposes into two independent axes ([`Align::axes`]), which is the form
32/// the arithmetic uses; the nine names exist because they are what a host says.
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
34pub enum Align {
35    #[default]
36    Center,
37    Top,
38    Bottom,
39    Left,
40    Right,
41    TopLeft,
42    TopRight,
43    BottomLeft,
44    BottomRight,
45}
46
47impl Align {
48    /// The horizontal and vertical axes, each `-1 | 0 | 1`.
49    ///
50    /// On the vertical axis **`-1` is the top of the view** — screen terms, not
51    /// maths terms, matching the Y-down space the player places itself in.
52    pub fn axes(self) -> (i8, i8) {
53        match self {
54            Align::Center => (0, 0),
55            Align::Top => (0, -1),
56            Align::Bottom => (0, 1),
57            Align::Left => (-1, 0),
58            Align::Right => (1, 0),
59            Align::TopLeft => (-1, -1),
60            Align::TopRight => (1, -1),
61            Align::BottomLeft => (-1, 1),
62            Align::BottomRight => (1, 1),
63        }
64    }
65}
66
67/// A box in **player-local** units — the space
68/// [`SSPlayer::part_transform`](crate::SSPlayer::part_transform) reports in, with
69/// `y` downward and the origin where the animation was authored around.
70#[derive(Clone, Copy, Debug, Default, PartialEq)]
71pub struct Rect {
72    /// Low edge on x.
73    pub x: f32,
74    /// Low edge on y, which is the **top** edge on screen.
75    pub y: f32,
76    pub width: f32,
77    pub height: f32,
78}
79
80/// Everything that places an animation inside a view.
81///
82/// The defaults are `contain`, centred, unscaled, unflipped, unrotated — so
83/// `Placement::default()` is "make it fit and put it in the middle", which is
84/// what a host reaching for this wants nine times out of ten.
85#[derive(Clone, Copy, Debug, PartialEq)]
86pub struct Placement {
87    pub fit: Fit,
88    pub align: Align,
89    /// The box to fit, in player-local units. **Supply it and nothing is
90    /// measured** — [`SSPlayer::fit_into`](crate::SSPlayer::fit_into) otherwise
91    /// falls back to the authored canvas
92    /// ([`SSPlayer::canvas_rect`](crate::SSPlayer::canvas_rect)).
93    pub frame: Option<Rect>,
94    /// Pixels from the aligned position, applied **after** the fit, so it is not
95    /// scaled by it.
96    pub offset: (f32, f32),
97    /// A multiplier **on top of** the fit's scale, not a replacement for it.
98    pub scale: f32,
99    /// Mirror horizontally. A flip is a negative scale on that axis, and the
100    /// alignment follows it — a left-aligned mirrored character still sits
101    /// against the left edge.
102    pub flip_x: bool,
103    /// Mirror vertically.
104    pub flip_y: bool,
105    /// Passed through to [`SSPlayer::set_transform`](crate::SSPlayer::set_transform)
106    /// untouched. Rotation has no part in the fit contract; it is here so that
107    /// fitting does not silently discard the rotation a caller already had.
108    pub rotation: f32,
109}
110
111impl Default for Placement {
112    fn default() -> Self {
113        Self { fit: Fit::default(), align: Align::default(), frame: None, offset: (0.0, 0.0), scale: 1.0, flip_x: false, flip_y: false, rotation: 0.0 }
114    }
115}
116
117/// A solved placement, in [`SSPlayer::set_transform`](crate::SSPlayer::set_transform)'s
118/// terms: pixels from the **view's centre**, `y` downward.
119///
120/// The conversion from the contract's view coordinates (origin at the view's
121/// top-left) happens once, in [`solve`]. Doing it anywhere else is the mistake
122/// that looks like a correct fit displaced by half a screen.
123#[derive(Clone, Copy, Debug, PartialEq)]
124pub struct Placed {
125    pub x: f32,
126    pub y: f32,
127    pub scale_x: f32,
128    pub scale_y: f32,
129}
130
131/// Solve one axis: where the content's origin lands, in view coordinates.
132///
133/// `scale` is **signed** — a flip is a negative scale, and which end of the box
134/// is the low one on screen depends on that sign, so the two cannot be solved
135/// separately and mirrored afterwards.
136fn axis(view: f32, scale: f32, lo: f32, size: f32, side: i8) -> f32 {
137    if side == 0 {
138        // Sign-independent, which is why centring is the safe default.
139        return view / 2.0 - scale * (lo + size / 2.0);
140    }
141    let (low_edge, high_edge) = if scale >= 0.0 { (lo, lo + size) } else { (lo + size, lo) };
142    if side < 0 { -scale * low_edge } else { view - scale * high_edge }
143}
144
145/// Fit `content` into a `view_width` x `view_height` box.
146///
147/// A zero-sized view, an absent or zero-sized box, and [`Fit::None`] all take the
148/// same path: **no fit**, origin at the view's centre, scale 1 before the
149/// caller's own. That is a documented outcome rather than an error — there is
150/// nothing to divide by and nothing to measure, and a host that laid out a
151/// collapsed box gets its animation back the moment the box has a size.
152pub fn solve(view_width: f32, view_height: f32, content: Option<Rect>, placement: &Placement) -> Placed {
153    let measured = content.filter(|rect| rect.width > 0.0 && rect.height > 0.0);
154    let fitted = match measured {
155        Some(rect) if placement.fit != Fit::None && view_width > 0.0 && view_height > 0.0 => {
156            let (sx, sy) = (view_width / rect.width, view_height / rect.height);
157            let scale = if placement.fit == Fit::Cover { sx.max(sy) } else { sx.min(sy) };
158            Some((rect, scale))
159        }
160        _ => None,
161    };
162
163    let scale = fitted.map_or(1.0, |(_, scale)| scale) * placement.scale;
164    let scale_x = if placement.flip_x { -scale } else { scale };
165    let scale_y = if placement.flip_y { -scale } else { scale };
166
167    let (origin_x, origin_y) = match fitted {
168        Some((rect, _)) => {
169            let (ax, ay) = placement.align.axes();
170            (axis(view_width, scale_x, rect.x, rect.width, ax), axis(view_height, scale_y, rect.y, rect.height, ay))
171        }
172        None => (view_width / 2.0, view_height / 2.0),
173    };
174
175    // `offset` is added last, to the solved origin; then the seam: `set_transform`
176    // measures from the view's centre, the contract from its top-left corner.
177    Placed { x: origin_x + placement.offset.0 - view_width / 2.0, y: origin_y + placement.offset.1 - view_height / 2.0, scale_x, scale_y }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    const VIEW: (f32, f32) = (400.0, 200.0);
185    /// Taller than it is wide, and not centred on the origin — so a mistake in the
186    /// box's low edge cannot hide behind a symmetric fixture.
187    const BOX: Rect = Rect { x: -100.0, y: -300.0, width: 200.0, height: 400.0 };
188
189    fn solved(placement: &Placement) -> Placed {
190        solve(VIEW.0, VIEW.1, Some(BOX), placement)
191    }
192
193    /// The two ratios are 400/200 = 2 on x and 200/400 = 0.5 on y, so `contain`
194    /// takes 0.5 and `cover` takes 2.
195    #[test]
196    fn contain_takes_the_smaller_ratio_and_cover_the_larger() {
197        assert_eq!(solved(&Placement::default()).scale_x, 0.5);
198        assert_eq!(solved(&Placement { fit: Fit::Cover, ..Default::default() }).scale_x, 2.0);
199    }
200
201    /// The box's centre lands on the view's centre, and the answer is in
202    /// `set_transform` terms — pixels from that centre — so it is zero here.
203    #[test]
204    fn centring_puts_the_boxs_middle_on_the_views_middle() {
205        let placed = solved(&Placement::default());
206        // Box centre is (0, -100) player-local, scaled by 0.5 → (0, -50) from the
207        // player's origin, so the origin sits 50 px below the view centre.
208        assert_eq!((placed.x, placed.y), (0.0, 50.0));
209    }
210
211    /// Each named alignment puts the corresponding edge of the scaled box on the
212    /// corresponding edge of the view.
213    #[test]
214    fn each_edge_alignment_lands_flush() {
215        let scale = 0.5;
216        for (align, (want_lo_x, want_lo_y)) in [
217            (Align::TopLeft, (0.0, 0.0)),
218            (Align::BottomRight, (VIEW.0 - BOX.width * scale, VIEW.1 - BOX.height * scale)),
219            (Align::Top, ((VIEW.0 - BOX.width * scale) / 2.0, 0.0)),
220            (Align::Right, (VIEW.0 - BOX.width * scale, (VIEW.1 - BOX.height * scale) / 2.0)),
221        ] {
222            let placed = solved(&Placement { align, ..Default::default() });
223            // Where the box's low corner landed, back in view coordinates.
224            let lo_x = placed.x + VIEW.0 / 2.0 + BOX.x * placed.scale_x;
225            let lo_y = placed.y + VIEW.1 / 2.0 + BOX.y * placed.scale_y;
226            assert!((lo_x - want_lo_x).abs() < 1e-3, "{align:?}: x {lo_x} != {want_lo_x}");
227            assert!((lo_y - want_lo_y).abs() < 1e-3, "{align:?}: y {lo_y} != {want_lo_y}");
228        }
229    }
230
231    /// A flip is a negative scale, and the alignment follows it: the mirrored box
232    /// still ends up against the left edge, not off it.
233    #[test]
234    fn a_flip_keeps_the_alignment_it_was_given() {
235        let placed = solved(&Placement { align: Align::Left, flip_x: true, ..Default::default() });
236        assert_eq!(placed.scale_x, -0.5);
237        let (a, b) = (placed.x + VIEW.0 / 2.0 + BOX.x * placed.scale_x, placed.x + VIEW.0 / 2.0 + (BOX.x + BOX.width) * placed.scale_x);
238        assert!((a.min(b) - 0.0).abs() < 1e-3, "left edge at {}", a.min(b));
239    }
240
241    /// Multiplies the fit rather than replacing it, and rides on top of a flip's
242    /// sign rather than cancelling it.
243    #[test]
244    fn scale_multiplies_the_fit() {
245        let placed = solved(&Placement { scale: 3.0, flip_y: true, ..Default::default() });
246        assert_eq!((placed.scale_x, placed.scale_y), (1.5, -1.5));
247    }
248
249    /// Pixels, applied after the fit, so it is not scaled by it.
250    #[test]
251    fn offset_is_added_after_the_fit() {
252        let base = solved(&Placement::default());
253        let moved = solved(&Placement { offset: (10.0, -20.0), ..Default::default() });
254        assert_eq!((moved.x - base.x, moved.y - base.y), (10.0, -20.0));
255    }
256
257    /// No box, no size, or `Fit::None` — all three answer "centred, unscaled"
258    /// rather than dividing by zero. The caller's own scale and offset still
259    /// apply, because with `none` they are the whole placement.
260    #[test]
261    fn the_degenerate_cases_centre_rather_than_fail() {
262        let centred = Placed { x: 0.0, y: 0.0, scale_x: 1.0, scale_y: 1.0 };
263        assert_eq!(solve(VIEW.0, VIEW.1, None, &Placement::default()), centred);
264        assert_eq!(solve(VIEW.0, VIEW.1, Some(Rect::default()), &Placement::default()), centred);
265        assert_eq!(solve(0.0, 0.0, Some(BOX), &Placement::default()), centred);
266        assert_eq!(solve(VIEW.0, VIEW.1, Some(BOX), &Placement { fit: Fit::None, ..Default::default() }), centred);
267
268        let placed = solve(VIEW.0, VIEW.1, Some(BOX), &Placement { fit: Fit::None, scale: 2.0, offset: (5.0, 5.0), ..Default::default() });
269        assert_eq!(placed, Placed { x: 5.0, y: 5.0, scale_x: 2.0, scale_y: 2.0 });
270    }
271}