Skip to main content

sim_logic/rendering/
screen.rs

1//! Managed presentation geometry in logical screen pixels.
2
3use std::{error::Error, fmt};
4
5use bevy_ecs::prelude::Component;
6use sim_engine::{Color, Layer, LogicalScreenPosition, LogicalScreenVector};
7
8use crate::input::PointerSample;
9
10#[path = "screen/image.rs"]
11mod image;
12pub use image::{ImageFilter, ImageRegion, ImageVisualError, ScreenImageVisual};
13#[path = "screen/clip.rs"]
14mod clip;
15#[path = "screen/rectangle.rs"]
16mod rectangle;
17pub use clip::ScreenClip;
18#[path = "screen/vectors.rs"]
19mod vectors;
20pub use vectors::{ScreenCircleVisual, ScreenLineVisual};
21#[path = "screen/polyline.rs"]
22mod polyline;
23pub use polyline::{ScreenPolylineError, ScreenPolylineVisual};
24
25/// A filled rectangle with optional rounded corners and a decorative outline.
26///
27/// The origin is the content area's top-left, with x increasing rightward and
28/// y downward. Finite negative and offscreen positions are allowed. World
29/// camera movement, zoom, rotation, and fixed interpolation do not affect this
30/// visual. It requires no world-space Transform and may coexist with a world
31/// visual on the same entity without controlling that visual.
32///
33/// FrameUpdate may mutate this presentation-only component directly. Extraction
34/// samples its current values, excludes disabled entities, and draws screen
35/// rectangles after all world visuals. Within screen content, lower layer and
36/// draw-order depth draw first; stable source identity breaks remaining ties.
37/// Visibility does not automatically capture or route input. No window or GPU
38/// is required to construct, update, or extract the component.
39#[derive(Debug, Clone, Copy, PartialEq, Component)]
40pub struct ScreenRectangleVisual {
41    position: LogicalScreenPosition,
42    size: LogicalScreenVector,
43    color: Color,
44    layer: Layer,
45    draw_order_depth: f32,
46    corner_radius: f32,
47    stroke: Option<sim_engine::Stroke>,
48    clip: ScreenClip,
49}
50
51impl ScreenRectangleVisual {
52    /// Creates a rectangle on the default layer with draw-order depth zero.
53    ///
54    /// Position must be finite, size must be finite and strictly positive on
55    /// both axes, and color must be normalized straight-linear RGBA. Adding
56    /// size to position in f32 must produce finite, strictly greater far bounds.
57    pub fn new(
58        position: LogicalScreenPosition,
59        size: LogicalScreenVector,
60        color: Color,
61    ) -> Result<Self, ScreenVisualError> {
62        let visual = Self {
63            position,
64            size,
65            color,
66            layer: Layer::DEFAULT,
67            draw_order_depth: 0.0,
68            corner_radius: 0.0,
69            stroke: None,
70            clip: ScreenClip::Unclipped,
71        };
72        visual.validate()?;
73        Ok(visual)
74    }
75
76    /// Returns the rectangle's top-left position in logical screen pixels.
77    pub const fn position(&self) -> LogicalScreenPosition {
78        self.position
79    }
80
81    /// Returns the full positive width and height in logical screen pixels.
82    pub const fn size(&self) -> LogicalScreenVector {
83        self.size
84    }
85
86    /// Tests the current rectangular geometry against an event-time pointer.
87    ///
88    /// Both the rectangle and the sample's stored viewport use half-open bounds:
89    /// left/top edges are included, right/bottom excluded. Partially offscreen
90    /// rectangles can be hit only inside that viewport. The supplied geometry
91    /// is current; this does not reconstruct historical layout after a resize.
92    ///
93    /// This is allocation-free geometry, not automatic UI routing. Alpha, entity
94    /// enablement and overlapping draw order are not inspected. The configured
95    /// clip and rounded fill are respected; the decorative outline is excluded.
96    /// The caller chooses eligibility and which overlapping target wins.
97    pub fn contains_pointer(&self, sample: PointerSample) -> bool {
98        if !self.clip.contains_pointer(sample) {
99            return false;
100        }
101        let point = sample.position().to_vec2();
102        let minimum = self.position.to_vec2();
103        let maximum = minimum + self.size.to_vec2();
104        let inside = point.x() >= minimum.x()
105            && point.y() >= minimum.y()
106            && point.x() < maximum.x()
107            && point.y() < maximum.y();
108        if !inside {
109            return false;
110        }
111        let radius = f64::from(self.corner_radius)
112            .min(f64::from(self.size.to_vec2().x()) * 0.5)
113            .min(f64::from(self.size.to_vec2().y()) * 0.5);
114        let x = f64::from(point.x()) - f64::from(minimum.x());
115        let y = f64::from(point.y()) - f64::from(minimum.y());
116        let dx = (x - x.clamp(radius, f64::from(self.size.to_vec2().x()) - radius)).abs();
117        let dy = (y - y.clamp(radius, f64::from(self.size.to_vec2().y()) - radius)).abs();
118        dx.hypot(dy) <= radius
119    }
120
121    /// Returns the normalized straight-linear RGBA fill color.
122    pub const fn color(&self) -> Color {
123        self.color
124    }
125
126    /// Returns the primary ordering layer within screen content.
127    pub const fn layer(&self) -> Layer {
128        self.layer
129    }
130
131    /// Returns the finite ordering depth within the screen layer.
132    ///
133    /// This value controls draw order only; it is not camera projection depth.
134    pub const fn draw_order_depth(&self) -> f32 {
135        self.draw_order_depth
136    }
137
138    /// Replaces position and size together after validating their bounds.
139    ///
140    /// Failure leaves every component value unchanged. Finite offscreen
141    /// geometry is accepted without clamping.
142    pub fn set_geometry(
143        &mut self,
144        position: LogicalScreenPosition,
145        size: LogicalScreenVector,
146    ) -> Result<(), ScreenVisualError> {
147        validate_geometry(position, size)?;
148        self.position = position;
149        self.size = size;
150        Ok(())
151    }
152
153    /// Replaces the logical top-left position while retaining size.
154    ///
155    /// Invalid or unrepresentable bounds leave the component unchanged.
156    pub fn set_position(
157        &mut self,
158        position: LogicalScreenPosition,
159    ) -> Result<(), ScreenVisualError> {
160        self.set_geometry(position, self.size)
161    }
162
163    /// Replaces logical width and height while retaining position.
164    ///
165    /// Non-positive size or invalid bounds leave the component unchanged.
166    pub fn set_size(&mut self, size: LogicalScreenVector) -> Result<(), ScreenVisualError> {
167        self.set_geometry(self.position, size)
168    }
169
170    /// Replaces normalized straight-linear RGBA color atomically.
171    ///
172    /// A non-finite channel or channel outside `0.0..=1.0` leaves it unchanged.
173    pub fn set_color(&mut self, color: Color) -> Result<(), ScreenVisualError> {
174        validate_color(color)?;
175        self.color = color;
176        Ok(())
177    }
178
179    /// Replaces the ordering layer within screen content.
180    pub fn set_layer(&mut self, layer: Layer) {
181        self.layer = layer;
182    }
183
184    /// Replaces within-layer ordering depth after finite-value validation.
185    ///
186    /// Negative values are allowed. Failure leaves the component unchanged.
187    pub fn set_draw_order_depth(&mut self, depth: f32) -> Result<(), ScreenVisualError> {
188        validate_draw_order_depth(depth)?;
189        self.draw_order_depth = depth;
190        Ok(())
191    }
192
193    pub(crate) fn validate(&self) -> Result<(), ScreenVisualError> {
194        validate_geometry(self.position, self.size)?;
195        validate_color(self.color)?;
196        validate_draw_order_depth(self.draw_order_depth)
197    }
198}
199
200/// Invalid value rejected by a screen visual's constructor or atomic setter.
201#[derive(Debug, Clone, Copy, PartialEq)]
202#[non_exhaustive]
203pub enum ScreenVisualError {
204    /// Removing the stroke would leave an outline-only shape with no paint.
205    MissingPaint,
206    /// Image rotation was non-finite.
207    InvalidRotation {
208        /// Rejected clockwise angle in radians.
209        value: f32,
210    },
211    /// Line endpoints coincide or their difference overflows.
212    InvalidLine,
213    /// A radius was negative or non-finite (circles additionally reject zero).
214    InvalidRadius {
215        /// Rejected radius in logical pixels.
216        value: f32,
217    },
218    /// A stroke width was non-finite or not positive.
219    InvalidStrokeWidth {
220        /// Rejected width in logical pixels.
221        value: f32,
222    },
223    /// A logical screen position contained a non-finite coordinate.
224    InvalidPosition {
225        /// Rejected logical top-left position.
226        value: LogicalScreenPosition,
227    },
228    /// A logical width or height was non-finite or not strictly positive.
229    InvalidSize {
230        /// Rejected logical-pixel size.
231        value: LogicalScreenVector,
232    },
233    /// Adding size overflowed or failed to advance either f32 coordinate.
234    InvalidBounds {
235        /// Logical top-left position of the rejected geometry.
236        position: LogicalScreenPosition,
237        /// Logical-pixel size of the rejected geometry.
238        size: LogicalScreenVector,
239    },
240    /// A color channel was non-finite or outside `0.0..=1.0`.
241    InvalidColor {
242        /// Rejected straight-linear RGBA color.
243        value: Color,
244    },
245    /// Draw-order depth was non-finite.
246    InvalidDrawOrderDepth {
247        /// Rejected ordering value.
248        value: f32,
249    },
250}
251
252impl fmt::Display for ScreenVisualError {
253    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
254        match self {
255            Self::MissingPaint => formatter.write_str("an outline-only shape requires a stroke"),
256            Self::InvalidRotation { value } => {
257                write!(formatter, "non-finite screen rotation: {value}")
258            }
259            Self::InvalidLine => formatter
260                .write_str("screen line endpoints must be distinct with finite displacement"),
261            Self::InvalidRadius { value } => write!(formatter, "invalid screen radius: {value}"),
262            Self::InvalidStrokeWidth { value } => {
263                write!(formatter, "invalid screen stroke width: {value}")
264            }
265            Self::InvalidPosition { value } => {
266                write!(
267                    formatter,
268                    "logical screen position must be finite, got {value:?}"
269                )
270            }
271            Self::InvalidSize { value } => write!(
272                formatter,
273                "logical screen size must be positive and finite, got {value:?}"
274            ),
275            Self::InvalidBounds { position, size } => write!(
276                formatter,
277                "logical screen bounds must be finite and strictly increasing, got {position:?} plus {size:?}"
278            ),
279            Self::InvalidColor { value } => write!(
280                formatter,
281                "screen color must be normalized linear RGBA, got {value:?}"
282            ),
283            Self::InvalidDrawOrderDepth { value } => {
284                write!(
285                    formatter,
286                    "screen draw-order depth must be finite, got {value}"
287                )
288            }
289        }
290    }
291}
292
293impl Error for ScreenVisualError {}
294
295fn validate_geometry(
296    position: LogicalScreenPosition,
297    size: LogicalScreenVector,
298) -> Result<(), ScreenVisualError> {
299    if !position.is_finite() {
300        return Err(ScreenVisualError::InvalidPosition { value: position });
301    }
302    let extent = size.to_vec2();
303    if !size.is_finite() || extent.x() <= 0.0 || extent.y() <= 0.0 {
304        return Err(ScreenVisualError::InvalidSize { value: size });
305    }
306    let minimum = position.to_vec2();
307    let maximum = minimum + extent;
308    if !maximum.is_finite() || maximum.x() <= minimum.x() || maximum.y() <= minimum.y() {
309        return Err(ScreenVisualError::InvalidBounds { position, size });
310    }
311    Ok(())
312}
313
314fn validate_color(value: Color) -> Result<(), ScreenVisualError> {
315    value
316        .is_normalized()
317        .then_some(())
318        .ok_or(ScreenVisualError::InvalidColor { value })
319}
320
321fn validate_draw_order_depth(value: f32) -> Result<(), ScreenVisualError> {
322    value
323        .is_finite()
324        .then_some(())
325        .ok_or(ScreenVisualError::InvalidDrawOrderDepth { value })
326}
327
328#[cfg(test)]
329mod tests {
330    use super::*;
331
332    fn state_bits(visual: ScreenRectangleVisual) -> [u32; 9] {
333        let position = visual.position().to_vec2();
334        let size = visual.size().to_vec2();
335        [
336            position.x(),
337            position.y(),
338            size.x(),
339            size.y(),
340            visual.color().red(),
341            visual.color().green(),
342            visual.color().blue(),
343            visual.color().alpha(),
344            visual.draw_order_depth(),
345        ]
346        .map(f32::to_bits)
347    }
348
349    #[test]
350    fn finite_offscreen_and_small_representable_geometry_is_preserved()
351    -> Result<(), ScreenVisualError> {
352        let position = LogicalScreenPosition::new(-40.0, 9_000.0);
353        let size = LogicalScreenVector::new(20.0, 10.0);
354        let mut visual = ScreenRectangleVisual::new(position, size, Color::WHITE)?;
355        assert_eq!(visual.position(), position);
356        assert_eq!(visual.size(), size);
357        assert_eq!(visual.layer(), Layer::DEFAULT);
358        assert_eq!(visual.draw_order_depth(), 0.0);
359
360        let subnormal = f32::from_bits(1);
361        visual.set_geometry(
362            LogicalScreenPosition::new(-0.0, 0.0),
363            LogicalScreenVector::new(subnormal, subnormal),
364        )?;
365        assert_eq!(
366            visual.position().to_vec2().x().to_bits(),
367            (-0.0_f32).to_bits()
368        );
369        assert_eq!(visual.size().to_vec2().x().to_bits(), 1);
370        visual.set_layer(Layer::new(-3));
371        visual.set_draw_order_depth(-2.0)?;
372        visual.set_color(Color::TRANSPARENT)?;
373        assert_eq!(visual.layer(), Layer::new(-3));
374        assert_eq!(visual.draw_order_depth(), -2.0);
375        assert_eq!(visual.color(), Color::TRANSPARENT);
376        Ok(())
377    }
378
379    #[test]
380    fn constructors_reject_nonfinite_nonpositive_and_unrepresentable_geometry() {
381        let origin = LogicalScreenPosition::default();
382        let unit = LogicalScreenVector::new(1.0, 1.0);
383        for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
384            for position in [
385                LogicalScreenPosition::new(value, 0.0),
386                LogicalScreenPosition::new(0.0, value),
387            ] {
388                assert!(matches!(
389                    ScreenRectangleVisual::new(position, unit, Color::WHITE),
390                    Err(ScreenVisualError::InvalidPosition { .. })
391                ));
392            }
393        }
394        for value in [0.0, -0.0, -1.0, f32::NAN, f32::INFINITY] {
395            for size in [
396                LogicalScreenVector::new(value, 1.0),
397                LogicalScreenVector::new(1.0, value),
398            ] {
399                assert!(matches!(
400                    ScreenRectangleVisual::new(origin, size, Color::WHITE),
401                    Err(ScreenVisualError::InvalidSize { .. })
402                ));
403            }
404        }
405        for (position, size) in [
406            (
407                LogicalScreenPosition::new(f32::MAX, 0.0),
408                LogicalScreenVector::new(f32::MAX, 1.0),
409            ),
410            (
411                LogicalScreenPosition::new(0.0, f32::MAX),
412                LogicalScreenVector::new(1.0, f32::MAX),
413            ),
414            (LogicalScreenPosition::new(16_777_216.0, 0.0), unit),
415            (LogicalScreenPosition::new(0.0, 16_777_216.0), unit),
416        ] {
417            assert!(matches!(
418                ScreenRectangleVisual::new(position, size, Color::WHITE),
419                Err(ScreenVisualError::InvalidBounds { .. })
420            ));
421        }
422        assert!(matches!(
423            ScreenRectangleVisual::new(origin, unit, Color::rgb(2.0, 0.0, 0.0)),
424            Err(ScreenVisualError::InvalidColor { .. })
425        ));
426    }
427
428    #[test]
429    fn failed_setters_preserve_every_prior_bit() -> Result<(), ScreenVisualError> {
430        let mut visual = ScreenRectangleVisual::new(
431            LogicalScreenPosition::new(-0.0, -0.0),
432            LogicalScreenVector::new(16.0, 8.0),
433            Color::rgba(-0.0, 0.25, 0.5, 1.0),
434        )?;
435        visual.set_draw_order_depth(-0.0)?;
436        visual.set_layer(Layer::new(7));
437        let before = state_bits(visual);
438        assert!(
439            visual
440                .set_geometry(
441                    LogicalScreenPosition::new(3.0, 4.0),
442                    LogicalScreenVector::new(0.0, 1.0)
443                )
444                .is_err()
445        );
446        assert_eq!(state_bits(visual), before);
447        assert!(
448            visual
449                .set_position(LogicalScreenPosition::new(f32::MAX, 0.0))
450                .is_err()
451        );
452        assert_eq!(state_bits(visual), before);
453        assert!(
454            visual
455                .set_size(LogicalScreenVector::new(1.0, f32::NAN))
456                .is_err()
457        );
458        assert_eq!(state_bits(visual), before);
459        for value in [f32::NAN, f32::INFINITY, -0.1, 1.1] {
460            assert!(visual.set_color(Color::WHITE.with_alpha(value)).is_err());
461            assert_eq!(state_bits(visual), before);
462        }
463        for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
464            assert!(visual.set_draw_order_depth(value).is_err());
465            assert_eq!(state_bits(visual), before);
466        }
467        assert_eq!(visual.layer(), Layer::new(7));
468        Ok(())
469    }
470
471    #[test]
472    fn geometry_setter_validates_the_requested_pair_together() -> Result<(), ScreenVisualError> {
473        let mut visual = ScreenRectangleVisual::new(
474            LogicalScreenPosition::default(),
475            LogicalScreenVector::new(1.0, 1.0),
476            Color::WHITE,
477        )?;
478        let position = LogicalScreenPosition::new(16_777_216.0, 16_777_216.0);
479        let size = LogicalScreenVector::new(2.0, 2.0);
480        assert!(visual.set_position(position).is_err());
481        visual.set_geometry(position, size)?;
482        assert_eq!(visual.position(), position);
483        assert_eq!(visual.size(), size);
484        assert!(visual.set_size(LogicalScreenVector::new(1.0, 1.0)).is_err());
485        assert_eq!(visual.size(), size);
486        Ok(())
487    }
488}