Skip to main content

sim_logic/rendering/screen/
vectors.rs

1//! Presentation-only vectors, independent of fixed-step world transforms.
2
3use super::{
4    ScreenClip, ScreenVisualError, rectangle::validate_stroke, validate_color,
5    validate_draw_order_depth,
6};
7use bevy_ecs::prelude::Component;
8use sim_engine::{
9    Color, Layer, LogicalPixels, LogicalScreenPosition, SceneError, ScreenScene, ShapeStyle, Stroke,
10};
11
12/// A round-ended line in top-left/downward logical screen pixels.
13///
14/// FrameUpdate can move it while simulation is paused. No Transform2d or camera
15/// is required. Draw order shares layer/depth/source ordering with the screen UI.
16/// Values are CPU-only; Engine performs its authoritative portability check at extraction.
17#[derive(Debug, Clone, Copy, PartialEq, Component)]
18pub struct ScreenLineVisual {
19    start: LogicalScreenPosition,
20    end: LogicalScreenPosition,
21    stroke: Stroke,
22    layer: Layer,
23    depth: f32,
24    clip: ScreenClip,
25}
26
27impl ScreenLineVisual {
28    /// Returns the primary mixed-screen ordering layer.
29    pub const fn layer(&self) -> Layer {
30        self.layer
31    }
32    /// Sets the primary mixed-screen ordering layer.
33    pub fn set_layer(&mut self, layer: Layer) {
34        self.layer = layer;
35    }
36    /// Returns finite within-layer ordering depth, not camera depth.
37    pub const fn draw_order_depth(&self) -> f32 {
38        self.depth
39    }
40    /// Sets within-layer depth atomically; nonfinite values are rejected.
41    pub fn set_draw_order_depth(&mut self, depth: f32) -> Result<(), ScreenVisualError> {
42        validate_draw_order_depth(depth)?;
43        self.depth = depth;
44        Ok(())
45    }
46    /// Returns the explicit fixed-screen clip.
47    pub const fn clip(&self) -> ScreenClip {
48        self.clip
49    }
50    /// Sets the clip without changing geometry or ordering.
51    pub fn set_clip(&mut self, clip: ScreenClip) {
52        self.clip = clip;
53    }
54    /// Creates a nondegenerate line with a positive logical width and normalized color.
55    pub fn new(
56        start: LogicalScreenPosition,
57        end: LogicalScreenPosition,
58        width: f32,
59        color: Color,
60    ) -> Result<Self, ScreenVisualError> {
61        validate_endpoints(start, end)?;
62        let stroke = Stroke::new(width, color);
63        validate_stroke(stroke)?;
64        Ok(Self {
65            start,
66            end,
67            stroke,
68            layer: Layer::DEFAULT,
69            depth: 0.0,
70            clip: ScreenClip::Unclipped,
71        })
72    }
73    /// Returns the first endpoint in logical pixels.
74    pub const fn start(&self) -> LogicalScreenPosition {
75        self.start
76    }
77    /// Returns the second endpoint in logical pixels.
78    pub const fn end(&self) -> LogicalScreenPosition {
79        self.end
80    }
81    /// Returns logical width and normalized line color.
82    pub const fn stroke(&self) -> Stroke {
83        self.stroke
84    }
85    /// Sets both endpoints atomically; nonfinite or coincident endpoints are rejected.
86    pub fn set_endpoints(
87        &mut self,
88        start: LogicalScreenPosition,
89        end: LogicalScreenPosition,
90    ) -> Result<(), ScreenVisualError> {
91        validate_endpoints(start, end)?;
92        self.start = start;
93        self.end = end;
94        Ok(())
95    }
96    /// Sets logical width and color atomically.
97    pub fn set_stroke(&mut self, stroke: Stroke) -> Result<(), ScreenVisualError> {
98        validate_stroke(stroke)?;
99        self.stroke = stroke;
100        Ok(())
101    }
102    /// Tests the clipped round-ended stroke, independently of entity/input routing.
103    pub fn contains_pointer(&self, sample: crate::input::PointerSample) -> bool {
104        if !self.clip.contains_pointer(sample) {
105            return false;
106        }
107        let a = self.start.to_vec2();
108        let b = self.end.to_vec2();
109        let p = sample.position().to_vec2();
110        let dx = f64::from(b.x()) - f64::from(a.x());
111        let dy = f64::from(b.y()) - f64::from(a.y());
112        let px = f64::from(p.x()) - f64::from(a.x());
113        let py = f64::from(p.y()) - f64::from(a.y());
114        let t = ((px * dx + py * dy) / (dx * dx + dy * dy)).clamp(0.0, 1.0);
115        (px - t * dx).hypot(py - t * dy) <= f64::from(self.stroke.width()) * 0.5
116    }
117    pub(crate) fn append(&self, scene: &mut ScreenScene) -> Result<(), SceneError> {
118        if !apply_clip(scene, self.clip)? {
119            return Ok(());
120        }
121        let width = LogicalPixels::new(self.stroke.width())
122            .map_err(|_| SceneError::InvalidStroke(sim_engine::ScenePrimitive::Line))?;
123        scene.try_line_on_layer(self.layer, self.start, self.end, width, self.stroke.color())
124    }
125}
126
127fn validate_endpoints(
128    start: LogicalScreenPosition,
129    end: LogicalScreenPosition,
130) -> Result<(), ScreenVisualError> {
131    for value in [start, end] {
132        if !value.is_finite() {
133            return Err(ScreenVisualError::InvalidPosition { value });
134        }
135    }
136    if start == end || !(end.to_vec2() - start.to_vec2()).is_finite() {
137        return Err(ScreenVisualError::InvalidLine);
138    }
139    Ok(())
140}
141
142/// A filled or outline-only circle in logical screen pixels.
143/// FrameUpdate may animate center/radius/color even when fixed simulation is paused.
144#[derive(Debug, Clone, Copy, PartialEq, Component)]
145pub struct ScreenCircleVisual {
146    center: LogicalScreenPosition,
147    radius: f32,
148    color: Color,
149    filled: bool,
150    stroke: Option<Stroke>,
151    layer: Layer,
152    depth: f32,
153    clip: ScreenClip,
154}
155
156impl ScreenCircleVisual {
157    /// Returns the primary mixed-screen ordering layer.
158    pub const fn layer(&self) -> Layer {
159        self.layer
160    }
161    /// Sets the primary mixed-screen ordering layer.
162    pub fn set_layer(&mut self, layer: Layer) {
163        self.layer = layer;
164    }
165    /// Returns finite within-layer ordering depth, not camera depth.
166    pub const fn draw_order_depth(&self) -> f32 {
167        self.depth
168    }
169    /// Sets within-layer depth atomically; nonfinite values are rejected.
170    pub fn set_draw_order_depth(&mut self, depth: f32) -> Result<(), ScreenVisualError> {
171        validate_draw_order_depth(depth)?;
172        self.depth = depth;
173        Ok(())
174    }
175    /// Returns the explicit fixed-screen clip.
176    pub const fn clip(&self) -> ScreenClip {
177        self.clip
178    }
179    /// Sets the clip without changing geometry or ordering.
180    pub fn set_clip(&mut self, clip: ScreenClip) {
181        self.clip = clip;
182    }
183    /// Creates a circle with finite center, positive finite radius, and normalized fill.
184    pub fn new(
185        center: LogicalScreenPosition,
186        radius: f32,
187        color: Color,
188    ) -> Result<Self, ScreenVisualError> {
189        validate_circle(center, radius)?;
190        validate_color(color)?;
191        Ok(Self {
192            center,
193            radius,
194            color,
195            filled: true,
196            stroke: None,
197            layer: Layer::DEFAULT,
198            depth: 0.0,
199            clip: ScreenClip::Unclipped,
200        })
201    }
202    /// Returns the logical screen center.
203    ///
204    /// For an outline-only circle this is also the stroke's center of symmetry.
205    pub const fn center(&self) -> LogicalScreenPosition {
206        self.center
207    }
208    /// Returns the positive logical radius.
209    pub const fn radius(&self) -> f32 {
210        self.radius
211    }
212    /// Returns the stored fill color (inactive for an outline-only circle).
213    pub const fn color(&self) -> Color {
214        self.color
215    }
216    /// Creates a centered circular outline without a filled disk.
217    /// Width/radius must be finite and positive; color is normalized linear RGBA.
218    pub fn outlined(
219        center: LogicalScreenPosition,
220        radius: f32,
221        width: f32,
222        color: Color,
223    ) -> Result<Self, ScreenVisualError> {
224        let mut circle = Self::new(center, radius, Color::TRANSPARENT)?;
225        let stroke = Stroke::new(width, color);
226        validate_stroke(stroke)?;
227        circle.filled = false;
228        circle.stroke = Some(stroke);
229        Ok(circle)
230    }
231    /// Returns active fill color, or None for an outline-only circle.
232    pub const fn fill_color(&self) -> Option<Color> {
233        if self.filled { Some(self.color) } else { None }
234    }
235    /// Atomically changes center and radius, preserving old values on failure.
236    pub fn set_geometry(
237        &mut self,
238        center: LogicalScreenPosition,
239        radius: f32,
240    ) -> Result<(), ScreenVisualError> {
241        validate_circle(center, radius)?;
242        self.center = center;
243        self.radius = radius;
244        Ok(())
245    }
246    /// Changes only the logical screen center, atomically.
247    pub fn set_center(&mut self, center: LogicalScreenPosition) -> Result<(), ScreenVisualError> {
248        self.set_geometry(center, self.radius)
249    }
250    /// Changes only the logical radius, atomically.
251    pub fn set_radius(&mut self, radius: f32) -> Result<(), ScreenVisualError> {
252        self.set_geometry(self.center, radius)
253    }
254    /// Sets and enables normalized fill color; rejection preserves all previous state.
255    pub fn set_color(&mut self, color: Color) -> Result<(), ScreenVisualError> {
256        validate_color(color)?;
257        self.color = color;
258        self.filled = true;
259        Ok(())
260    }
261    /// Returns the optional decorative outline.
262    pub const fn stroke(&self) -> Option<Stroke> {
263        self.stroke
264    }
265    /// Sets a positive-width normalized-color outline, or removes it with None.
266    /// An outline-only circle rejects removal until a fill is enabled.
267    pub fn set_stroke(&mut self, stroke: Option<Stroke>) -> Result<(), ScreenVisualError> {
268        if !self.filled && stroke.is_none() {
269            return Err(ScreenVisualError::MissingPaint);
270        }
271        if let Some(stroke) = stroke {
272            validate_stroke(stroke)?;
273        }
274        self.stroke = stroke;
275        Ok(())
276    }
277    /// Tests the clipped disk for filled circles, or the centered annulus for
278    /// outline-only circles. Does not inspect alpha, MSAA or painter priority.
279    pub fn contains_pointer(&self, sample: crate::input::PointerSample) -> bool {
280        if !self.clip.contains_pointer(sample) {
281            return false;
282        }
283        let p = sample.position().to_vec2();
284        let c = self.center.to_vec2();
285        let distance =
286            (f64::from(p.x()) - f64::from(c.x())).hypot(f64::from(p.y()) - f64::from(c.y()));
287        if self.filled {
288            distance <= f64::from(self.radius)
289        } else {
290            self.stroke.is_some_and(|stroke| {
291                (distance - f64::from(self.radius)).abs() <= f64::from(stroke.width()) * 0.5
292            })
293        }
294    }
295    pub(crate) fn append(&self, scene: &mut ScreenScene) -> Result<(), SceneError> {
296        if !apply_clip(scene, self.clip)? {
297            return Ok(());
298        }
299        let style = if let (false, Some(stroke)) = (self.filled, self.stroke) {
300            ShapeStyle::stroked(stroke.width(), stroke.color())
301        } else {
302            self.stroke.map_or_else(
303                || ShapeStyle::filled(self.color),
304                |stroke| ShapeStyle::fill_stroke(self.color, stroke.width(), stroke.color()),
305            )
306        };
307        let radius = LogicalPixels::new(self.radius)
308            .map_err(|_| SceneError::InvalidDimension(sim_engine::ScenePrimitive::Circle))?;
309        scene.try_circle_on_layer(self.layer, self.center, radius, style)
310    }
311}
312
313fn validate_circle(center: LogicalScreenPosition, radius: f32) -> Result<(), ScreenVisualError> {
314    if !center.is_finite() {
315        return Err(ScreenVisualError::InvalidPosition { value: center });
316    }
317    if !radius.is_finite() || radius <= 0.0 {
318        return Err(ScreenVisualError::InvalidRadius { value: radius });
319    }
320    Ok(())
321}
322
323pub(super) fn apply_clip(scene: &mut ScreenScene, clip: ScreenClip) -> Result<bool, SceneError> {
324    match clip {
325        ScreenClip::Empty => Ok(false),
326        ScreenClip::Unclipped => {
327            scene.set_screen_clip(None)?;
328            Ok(true)
329        }
330        ScreenClip::Rectangle(clip) => {
331            scene.set_screen_clip(Some(clip))?;
332            Ok(true)
333        }
334    }
335}