Skip to main content

sim_logic/rendering/screen/
image.rs

1//! Managed image placement using the same logical geometry as screen panels.
2
3use std::{error::Error, fmt};
4
5use bevy_ecs::prelude::Component;
6use sim_engine::{Color, Layer, LogicalScreenPosition, LogicalScreenVector};
7
8use crate::assets::ImageAssetId;
9
10use super::{ScreenRectangleVisual, ScreenVisualError};
11
12/// Sampling applied when a source image is scaled on screen.
13#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
14pub enum ImageFilter {
15    /// Select the nearest texel, preserving hard pixel boundaries by default.
16    #[default]
17    Nearest,
18    /// Blend neighboring texels when sampling the source image.
19    Linear,
20}
21
22/// An exact rectangular source region in image texels, with top-left origin.
23///
24/// Width and height are positive, and each origin plus extent fits in u32.
25/// The region must also fit the selected image when attached to a visual.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
27pub struct ImageRegion {
28    x: u32,
29    y: u32,
30    width: u32,
31    height: u32,
32}
33
34impl ImageRegion {
35    /// Creates a source region, rejecting zero extents and overflowing bounds.
36    ///
37    /// Coordinates are texels, not normalized UVs or logical screen pixels.
38    /// No image is sampled or allocated; image-specific bounds are checked by
39    /// [`ScreenImageVisual::set_source_region`].
40    pub fn new(x: u32, y: u32, width: u32, height: u32) -> Result<Self, ImageVisualError> {
41        let region = Self {
42            x,
43            y,
44            width,
45            height,
46        };
47        region.validate()?;
48        Ok(region)
49    }
50
51    /// Returns the leftmost source texel coordinate.
52    pub const fn x(self) -> u32 {
53        self.x
54    }
55
56    /// Returns the topmost source texel coordinate.
57    pub const fn y(self) -> u32 {
58        self.y
59    }
60
61    /// Returns the positive source width in texels.
62    pub const fn width(self) -> u32 {
63        self.width
64    }
65
66    /// Returns the positive source height in texels.
67    pub const fn height(self) -> u32 {
68        self.height
69    }
70
71    fn validate(self) -> Result<(), ImageVisualError> {
72        if self.width == 0
73            || self.height == 0
74            || self.x.checked_add(self.width).is_none()
75            || self.y.checked_add(self.height).is_none()
76        {
77            return Err(ImageVisualError::InvalidRegion {
78                x: self.x,
79                y: self.y,
80                width: self.width,
81                height: self.height,
82            });
83        }
84        Ok(())
85    }
86
87    fn validate_image(self, image: ImageAssetId) -> Result<(), ImageVisualError> {
88        self.validate()?;
89        if self.x + self.width > image.width() || self.y + self.height > image.height() {
90            return Err(ImageVisualError::RegionOutOfBounds {
91                region: self,
92                image,
93            });
94        }
95        Ok(())
96    }
97}
98
99/// An immutable image drawn in logical screen pixels above world content.
100///
101/// Position is the top-left corner, x increases rightward, and y increases
102/// downward. Finite offscreen placement is allowed. Geometry, tint, layer, and
103/// draw-order depth use the same validation as [`ScreenRectangleVisual`]. The
104/// component needs no Transform, window, or GPU, and FrameUpdate may change it.
105/// Extraction samples current values and excludes disabled entities.
106///
107/// Construction validates image-region dimensions from the issued handle;
108/// extraction also checks that its application registry owns the image. A
109/// foreign handle is not made valid by constructing this component. Within
110/// screen content, layer, depth, and stable entity identity control ordering;
111/// a rectangle precedes an image on an exact same-entity tie. No input capture
112/// or hit testing is implied by visibility.
113#[derive(Debug, Clone, Copy, PartialEq, Component)]
114pub struct ScreenImageVisual {
115    rotation: f32,
116    image: ImageAssetId,
117    source_region: Option<ImageRegion>,
118    filter: ImageFilter,
119    rectangle: ScreenRectangleVisual,
120}
121
122impl ScreenImageVisual {
123    /// Returns clockwise radians about the destination rectangle's center.
124    /// The top-left position and size describe the unrotated rectangle.
125    pub const fn rotation(&self) -> f32 {
126        self.rotation
127    }
128
129    /// Sets clockwise center rotation, reducing finite angles to `0..TAU`.
130    /// No image pixels are recreated. Failure leaves the visual unchanged.
131    pub fn set_rotation(&mut self, radians: f32) -> Result<(), ImageVisualError> {
132        if !radians.is_finite() {
133            return Err(ScreenVisualError::InvalidRotation { value: radians }.into());
134        }
135        self.rotation = radians.rem_euclid(std::f32::consts::TAU);
136        Ok(())
137    }
138
139    /// Tests the rotated destination and fixed clip, not individual texel alpha.
140    /// The caller still selects eligibility and resolves overlapping targets.
141    pub fn contains_pointer(&self, sample: crate::input::PointerSample) -> bool {
142        if !self.clip().contains_pointer(sample) {
143            return false;
144        }
145        let size = self.size().to_vec2();
146        let min = self.position().to_vec2();
147        let p = sample.position().to_vec2();
148        let x = f64::from(p.x()) - (f64::from(min.x()) + f64::from(size.x()) * 0.5);
149        let y = f64::from(p.y()) - (f64::from(min.y()) + f64::from(size.y()) * 0.5);
150        let (sin, cos) = f64::from(self.rotation).sin_cos();
151        let local_x = x * cos + y * sin + f64::from(size.x()) * 0.5;
152        let local_y = -x * sin + y * cos + f64::from(size.y()) * 0.5;
153        local_x >= 0.0
154            && local_y >= 0.0
155            && local_x < f64::from(size.x())
156            && local_y < f64::from(size.y())
157    }
158    /// Returns the fixed-screen clip; content placement does not move it.
159    pub const fn clip(&self) -> super::ScreenClip {
160        self.rectangle.clip()
161    }
162
163    /// Replaces the screen clip, independent of source texels and destination.
164    pub fn set_clip(&mut self, clip: super::ScreenClip) {
165        self.rectangle.set_clip(clip);
166    }
167    /// Places the full image with white tint and nearest-texel sampling.
168    ///
169    /// The default layer and depth zero match screen rectangles. Position must
170    /// be finite; size must be positive and finite, with finite, increasing far
171    /// bounds. Geometry is independent from the image's texel dimensions.
172    pub fn new(
173        image: ImageAssetId,
174        position: LogicalScreenPosition,
175        size: LogicalScreenVector,
176    ) -> Result<Self, ImageVisualError> {
177        Ok(Self {
178            rotation: 0.0,
179            image,
180            source_region: None,
181            filter: ImageFilter::Nearest,
182            rectangle: ScreenRectangleVisual::new(position, size, Color::WHITE)?,
183        })
184    }
185
186    /// Returns the immutable application image handle used by this visual.
187    pub const fn image(&self) -> ImageAssetId {
188        self.image
189    }
190
191    /// Returns the source texel rectangle, or None for the complete image.
192    pub const fn source_region(&self) -> Option<ImageRegion> {
193        self.source_region
194    }
195
196    /// Returns the sampling policy used when scaling this image.
197    pub const fn filter(&self) -> ImageFilter {
198        self.filter
199    }
200
201    /// Returns the top-left destination in logical screen pixels.
202    pub const fn position(&self) -> LogicalScreenPosition {
203        self.rectangle.position()
204    }
205
206    /// Returns the positive destination width and height in logical pixels.
207    pub const fn size(&self) -> LogicalScreenVector {
208        self.rectangle.size()
209    }
210
211    /// Returns the normalized straight-linear RGBA multiplication tint.
212    pub const fn tint(&self) -> Color {
213        self.rectangle.color()
214    }
215
216    /// Returns the primary ordering layer within screen content.
217    pub const fn layer(&self) -> Layer {
218        self.rectangle.layer()
219    }
220
221    /// Returns the finite within-layer draw order, unrelated to camera depth.
222    pub const fn draw_order_depth(&self) -> f32 {
223        self.rectangle.draw_order_depth()
224    }
225
226    /// Replaces the image while retaining its source region and presentation.
227    ///
228    /// If the existing region does not fit the new image, nothing changes.
229    /// With no explicit region, the new image's complete extent is selected.
230    /// Application provenance is checked later by extraction.
231    pub fn set_image(&mut self, image: ImageAssetId) -> Result<(), ImageVisualError> {
232        if let Some(region) = self.source_region {
233            region.validate_image(image)?;
234        }
235        self.image = image;
236        Ok(())
237    }
238
239    /// Selects exact source texels, or resets to the full image with None.
240    ///
241    /// A region outside the selected image leaves every component field
242    /// unchanged. This changes sampling, not destination position or size.
243    pub fn set_source_region(
244        &mut self,
245        region: Option<ImageRegion>,
246    ) -> Result<(), ImageVisualError> {
247        if let Some(region) = region {
248            region.validate_image(self.image)?;
249        }
250        self.source_region = region;
251        Ok(())
252    }
253
254    /// Replaces the sampling policy without changing image or geometry.
255    pub fn set_filter(&mut self, filter: ImageFilter) {
256        self.filter = filter;
257    }
258
259    /// Replaces position and size together using screen rectangle validation.
260    ///
261    /// Invalid values leave the component unchanged. Finite negative and
262    /// offscreen positions are accepted without clamping or source cropping.
263    pub fn set_geometry(
264        &mut self,
265        position: LogicalScreenPosition,
266        size: LogicalScreenVector,
267    ) -> Result<(), ImageVisualError> {
268        self.rectangle.set_geometry(position, size)?;
269        Ok(())
270    }
271
272    /// Replaces position while retaining size; invalid bounds change nothing.
273    pub fn set_position(
274        &mut self,
275        position: LogicalScreenPosition,
276    ) -> Result<(), ImageVisualError> {
277        self.rectangle.set_position(position)?;
278        Ok(())
279    }
280
281    /// Replaces size while retaining position; invalid bounds change nothing.
282    pub fn set_size(&mut self, size: LogicalScreenVector) -> Result<(), ImageVisualError> {
283        self.rectangle.set_size(size)?;
284        Ok(())
285    }
286
287    /// Replaces normalized straight-linear RGBA tint atomically.
288    ///
289    /// A non-finite channel or value outside `0.0..=1.0` changes nothing.
290    pub fn set_tint(&mut self, tint: Color) -> Result<(), ImageVisualError> {
291        self.rectangle.set_color(tint)?;
292        Ok(())
293    }
294
295    /// Replaces the primary ordering layer within screen content.
296    pub fn set_layer(&mut self, layer: Layer) {
297        self.rectangle.set_layer(layer);
298    }
299
300    /// Replaces finite within-layer ordering depth; invalid input changes nothing.
301    ///
302    /// Negative depths are valid and do not change camera projection.
303    pub fn set_draw_order_depth(&mut self, depth: f32) -> Result<(), ImageVisualError> {
304        self.rectangle.set_draw_order_depth(depth)?;
305        Ok(())
306    }
307
308    pub(crate) fn validate(&self) -> Result<(), ImageVisualError> {
309        self.rectangle.validate()?;
310        if let Some(region) = self.source_region {
311            region.validate_image(self.image)?;
312        }
313        Ok(())
314    }
315}
316
317/// An invalid screen image value rejected before changing the visual.
318#[derive(Debug, Clone, Copy, PartialEq)]
319#[non_exhaustive]
320pub enum ImageVisualError {
321    /// Destination geometry, tint, or ordering failed screen validation.
322    Screen(ScreenVisualError),
323    /// A source region has zero extent or overflowing integer bounds.
324    InvalidRegion {
325        /// Rejected horizontal texel origin.
326        x: u32,
327        /// Rejected vertical texel origin.
328        y: u32,
329        /// Rejected texel width.
330        width: u32,
331        /// Rejected texel height.
332        height: u32,
333    },
334    /// A valid source region extends beyond the selected image dimensions.
335    RegionOutOfBounds {
336        /// Rejected source region in texels.
337        region: ImageRegion,
338        /// Image whose dimensions the region must fit.
339        image: ImageAssetId,
340    },
341}
342
343impl From<ScreenVisualError> for ImageVisualError {
344    fn from(source: ScreenVisualError) -> Self {
345        Self::Screen(source)
346    }
347}
348
349impl fmt::Display for ImageVisualError {
350    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
351        match self {
352            Self::Screen(source) => {
353                write!(formatter, "invalid screen image presentation: {source}")
354            }
355            Self::InvalidRegion {
356                x,
357                y,
358                width,
359                height,
360            } => write!(
361                formatter,
362                "image source region ({x}, {y}, {width}, {height}) needs positive extents and non-overflowing texel bounds"
363            ),
364            Self::RegionOutOfBounds { region, image } => write!(
365                formatter,
366                "image source region {region:?} exceeds image dimensions {} by {}",
367                image.width(),
368                image.height()
369            ),
370        }
371    }
372}
373
374impl Error for ImageVisualError {
375    fn source(&self) -> Option<&(dyn Error + 'static)> {
376        match self {
377            Self::Screen(source) => Some(source),
378            _ => None,
379        }
380    }
381}
382
383#[cfg(test)]
384#[path = "image_tests.rs"]
385mod tests;