concinnity_core/components/sprite.rs
1// Screen-space sprite overlay schema.
2
3use crate::ecs::TextureHandle;
4use crate::ecs::asset_id::AssetId;
5use crate::ecs::asset_id::de_opt_asset_ref;
6use crate::ecs::de_opt_texture_handle;
7
8/// Screen-space 2D rectangle drawn as a UI overlay each frame.
9///
10/// Sprites are pixel-anchored quads with an RGBA tint. They draw alongside
11/// [TextLabel](#textlabel)s, ordered behind labels so text sits on top.
12///
13/// A sprite with a `texture` draws that image, multiplied by the tint (use a
14/// white tint to show the image unchanged; the tint's alpha fades it).
15/// Without one, the tint is drawn as a solid-coloured rectangle.
16///
17/// ```rust
18/// # use concinnity_core::components::Sprite;
19/// Sprite {
20/// x: 0.0,
21/// y: 0.0,
22/// width: 1280.0,
23/// height: 720.0,
24/// tint: [0.04, 0.06, 0.1, 1.0],
25/// ..Default::default()
26/// };
27/// ```
28#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
29#[serde(default)]
30pub struct Sprite {
31 /// Assigned by the loader; not authored.
32 #[serde(skip)]
33 pub asset_id: AssetId,
34 /// Left edge in screen pixels from the window's top-left.
35 pub x: f32,
36 /// Top edge in screen pixels from the window's top-left.
37 pub y: f32,
38 /// Width in screen pixels.
39 pub width: f32,
40 /// Height in screen pixels.
41 pub height: f32,
42 /// [Texture](#texture) to draw, sampled over the sprite's rect and
43 /// multiplied by `tint`. Omitted, the sprite is a solid `tint` fill.
44 #[serde(deserialize_with = "de_opt_texture_handle")]
45 pub texture: Option<TextureHandle>,
46 /// RGBA colour the rectangle is filled with, each channel in [0, 1].
47 pub tint: [f32; 4],
48 /// When true, the sprite acts as an in-engine cursor: it is drawn on top of
49 /// the other overlays as an arrow pointer tracking the mouse, with the
50 /// pointer at the arrow's tip. `tint` is the arrow fill (a contrasting
51 /// outline is added automatically) and `height` its size; `width` is
52 /// ignored so the arrow keeps its shape. The system cursor is hidden while
53 /// a visible `follow_cursor` sprite exists.
54 pub follow_cursor: bool,
55 /// When false the sprite is skipped each frame.
56 pub visible: bool,
57 /// [Screen](#screen) this sprite belongs to. Resolved automatically from
58 /// the naming convention (`<screen>_*`); you don't set this directly.
59 /// `None` means the sprite is always visible (e.g. a scene background).
60 #[serde(default, deserialize_with = "de_opt_asset_ref")]
61 pub screen: Option<AssetId>,
62 /// How a screen-owned sprite maps from the reference canvas to the window
63 /// when their aspect ratios differ.
64 pub fit: SpriteFit,
65 /// Corner rounding radius in the sprite's own pixel space. `0` keeps
66 /// sharp corners; larger values round each corner with a quarter-circle
67 /// arc (clamped to half the sprite's shorter side). The rounded edge is
68 /// softly anti-aliased.
69 pub corner_radius: f32,
70 /// Border stroke width in the sprite's own pixel space, drawn just inside
71 /// the sprite's outline and following its rounded corners. `0` draws no
72 /// border; larger values inset the tinted fill by this width and paint the
73 /// ring in `border_color` (clamped to half the sprite's shorter side).
74 pub border_width: f32,
75 /// RGBA colour of the border stroke, each channel in [0, 1]. Ignored when
76 /// `border_width` is `0`.
77 pub border_color: [f32; 4],
78}
79
80/// How a screen-owned overlay element (a [Sprite](#sprite), [TextLabel](#textlabel),
81/// or [HitRegion](#hitregion)) maps from the 1280x720 reference canvas to the
82/// live window when their aspect ratios differ.
83///
84/// Screen-owned UI is authored against a fixed reference canvas and uniformly
85/// scaled to the window at runtime.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, Default)]
87#[serde(rename_all = "lowercase")]
88pub enum SpriteFit {
89 /// The canvas fits inside the window, centered, leaving margins on the
90 /// shorter axis. UI elements keep their proportions and stay fully
91 /// visible.
92 #[default]
93 Fit,
94 /// The canvas fills the window, centered, cropping the overflowing axis
95 /// equally on both sides. Full-bleed stage imagery (scene backdrops,
96 /// character portraits) reaches the window edges without distorting, and
97 /// content anchored to a canvas edge stays flush with the window edge.
98 Cover,
99 /// The canvas keeps the `fit` scale (no cropping), but the whole overlay is
100 /// shifted so the reference bottom edge lands on the window bottom edge.
101 /// Bottom-anchored furniture (a visual-novel dialog box and its controls)
102 /// hugs the window bottom at any aspect ratio instead of floating above a
103 /// letterbox margin.
104 Bottom,
105}
106
107impl Default for Sprite {
108 fn default() -> Self {
109 Self {
110 asset_id: AssetId::default(),
111 x: 0.0,
112 y: 0.0,
113 width: 100.0,
114 height: 100.0,
115 texture: None,
116 tint: [1.0, 1.0, 1.0, 1.0],
117 follow_cursor: false,
118 visible: true,
119 screen: None,
120 fit: SpriteFit::Fit,
121 corner_radius: 0.0,
122 border_width: 0.0,
123 border_color: [0.0, 0.0, 0.0, 1.0],
124 }
125 }
126}
127
128#[cfg(test)]
129mod tests {
130 use super::*;
131
132 #[test]
133 fn a_blank_sprite_is_a_visible_untinted_square_with_no_border() {
134 let s = Sprite::default();
135 assert_eq!((s.width, s.height), (100.0, 100.0));
136 assert_eq!(s.tint, [1.0, 1.0, 1.0, 1.0]);
137 assert!(s.visible);
138 assert!(!s.follow_cursor);
139 assert_eq!(s.fit, SpriteFit::Fit);
140 assert_eq!(s.corner_radius, 0.0);
141 // Zero width is what suppresses the border, so its colour is irrelevant.
142 assert_eq!(s.border_width, 0.0);
143 assert!(s.texture.is_none());
144 assert!(s.screen.is_none());
145 assert_eq!(SpriteFit::default(), SpriteFit::Fit);
146 }
147
148 #[test]
149 fn fit_names_parse_in_lowercase() {
150 let f = |s: &str| serde_json::from_str::<SpriteFit>(s).unwrap();
151 assert_eq!(f(r#""fit""#), SpriteFit::Fit);
152 assert_eq!(f(r#""cover""#), SpriteFit::Cover);
153 assert_eq!(f(r#""bottom""#), SpriteFit::Bottom);
154 assert_eq!(
155 serde_json::to_string(&SpriteFit::Bottom).unwrap(),
156 r#""bottom""#
157 );
158 }
159
160 #[test]
161 fn a_cursor_sprite_parses_and_round_trips_through_postcard() {
162 crate::test_support::install_resolvers();
163 let s: Sprite = serde_json::from_str(
164 r#"{"x":10,"y":20,"width":32,"height":32,"texture":"tex_cursor",
165 "tint":[1,1,1,0.8],"follow_cursor":true,"visible":false,"screen":"menu",
166 "fit":"cover","corner_radius":4,"border_width":2,"border_color":[1,0,0,1]}"#,
167 )
168 .unwrap();
169 assert_eq!(s.texture, Some(TextureHandle(10)));
170 assert_eq!(s.screen, Some(AssetId(4)));
171 assert!(s.follow_cursor);
172 assert!(!s.visible);
173
174 let bytes = postcard::to_allocvec(&s).unwrap();
175 let back: Sprite = postcard::from_bytes(&bytes).unwrap();
176 assert_eq!((back.x, back.y), (10.0, 20.0));
177 assert_eq!(back.tint, [1.0, 1.0, 1.0, 0.8]);
178 assert_eq!(back.fit, SpriteFit::Cover);
179 assert_eq!(back.corner_radius, 4.0);
180 assert_eq!(back.border_width, 2.0);
181 assert_eq!(back.border_color, [1.0, 0.0, 0.0, 1.0]);
182 assert_eq!(back.asset_id, AssetId::default());
183 }
184}