Skip to main content

sim_logic/rendering/screen/
polyline.rs

1//! Shared CPU paths; Engine alone validates and tessellates their strokes.
2
3use super::{ScreenClip, ScreenVisualError, validate_draw_order_depth, vectors::apply_clip};
4use bevy_ecs::prelude::Component;
5use sim_engine::{Color, Layer, LogicalScreenPosition, SceneError, ScreenScene, StrokeStyle2d};
6use std::{error::Error, fmt, sync::Arc};
7
8/// One open line strip in top-left/downward logical screen pixels.
9///
10/// One component represents the whole path, with continuous joins/dashes and
11/// only two endpoint caps. Two points provide a styled line. Engine owns stroke
12/// validation, clipping and tessellation. Repeating the first point at the end
13/// is rejected: Engine 0.4.2 has no closed styled-path contract.
14///
15/// Clones share immutable points and style; setters validate before replacing state.
16/// World cameras and fixed interpolation do not transform these coordinates.
17/// CPU creation requires no window or GPU.
18#[derive(Debug, Clone, PartialEq, Component)]
19pub struct ScreenPolylineVisual {
20    points: Arc<Vec<LogicalScreenPosition>>,
21    // Keep the large dash/marker value outside the common primitive enum.
22    // Simple rectangles/lines must not pay for unused path-style storage.
23    style: Arc<StrokeStyle2d>,
24    max_points: usize,
25    layer: Layer,
26    depth: f32,
27    clip: ScreenClip,
28}
29
30impl ScreenPolylineVisual {
31    /// Default per-path point ceiling; aggregate extraction limits are separate.
32    pub const DEFAULT_MAX_POINTS: usize = 65_536;
33
34    /// Copies a bounded open path with explicit logical stroke style.
35    /// Invalid geometry/style, world-unit widths and point-buffer reservation
36    /// failures are errors. Small shared metadata uses Rust's ordinary allocator.
37    pub fn new(
38        points: &[LogicalScreenPosition],
39        style: StrokeStyle2d,
40    ) -> Result<Self, ScreenPolylineError> {
41        Self::with_point_limit(points, style, Self::DEFAULT_MAX_POINTS)
42    }
43    /// Creates a path with an immutable point-count ceiling, at least two.
44    /// This is not an application quota; set aggregate RenderLimits separately.
45    pub fn with_point_limit(
46        points: &[LogicalScreenPosition],
47        style: StrokeStyle2d,
48        max_points: usize,
49    ) -> Result<Self, ScreenPolylineError> {
50        validate(points, style, max_points)?;
51        Ok(Self {
52            points: copy_points(points)?,
53            style: Arc::new(style),
54            max_points,
55            layer: Layer::DEFAULT,
56            depth: 0.0,
57            clip: ScreenClip::Unclipped,
58        })
59    }
60    /// Borrows all immutable logical-screen points.
61    pub fn points(&self) -> &[LogicalScreenPosition] {
62        &self.points
63    }
64    /// Returns the fixed per-path point-count ceiling.
65    pub const fn max_points(&self) -> usize {
66        self.max_points
67    }
68    /// Returns logical width/color, caps, joins, dashes and markers.
69    pub fn style(&self) -> StrokeStyle2d {
70        *self.style
71    }
72    /// Returns point Vec capacity bytes, excluding shared-Arc metadata.
73    /// Clones report shared storage; do not sum them as independent allocations.
74    pub fn point_allocation_bytes(&self) -> usize {
75        self.points
76            .capacity()
77            .saturating_mul(size_of::<LogicalScreenPosition>())
78    }
79    /// Atomically copies new points. Equal points skip validation and copying.
80    pub fn set_points(
81        &mut self,
82        points: &[LogicalScreenPosition],
83    ) -> Result<(), ScreenPolylineError> {
84        if self.points() == points {
85            return Ok(());
86        }
87        validate(points, *self.style, self.max_points)?;
88        self.points = copy_points(points)?;
89        Ok(())
90    }
91    /// Atomically changes style, preserving shared point storage.
92    pub fn set_style(&mut self, style: StrokeStyle2d) -> Result<(), ScreenPolylineError> {
93        if *self.style == style {
94            return Ok(());
95        }
96        validate(self.points(), style, self.max_points)?;
97        *Arc::make_mut(&mut self.style) = style;
98        Ok(())
99    }
100    /// Returns the mixed-screen ordering layer.
101    pub const fn layer(&self) -> Layer {
102        self.layer
103    }
104    /// Sets the layer without copying points.
105    pub fn set_layer(&mut self, layer: Layer) {
106        self.layer = layer;
107    }
108    /// Returns within-layer ordering depth, not camera depth.
109    pub const fn draw_order_depth(&self) -> f32 {
110        self.depth
111    }
112    /// Sets finite ordering depth; rejection leaves the old value intact.
113    pub fn set_draw_order_depth(&mut self, depth: f32) -> Result<(), ScreenVisualError> {
114        validate_draw_order_depth(depth)?;
115        self.depth = depth;
116        Ok(())
117    }
118    /// Returns the fixed logical-screen clip.
119    pub const fn clip(&self) -> ScreenClip {
120        self.clip
121    }
122    /// Sets clipping without copying or moving points.
123    pub fn set_clip(&mut self, clip: ScreenClip) {
124        self.clip = clip;
125    }
126
127    /// Picks the clipped centerline within a finite nonnegative logical radius.
128    ///
129    /// This is editor selection, not painted-pixel coverage: it includes dash
130    /// gaps and endpoint disks, ignoring caps, joins, markers, alpha and stroke
131    /// width. Supply the selection radius explicitly. Work is linear in the
132    /// bounded point count, without allocations or GPU access.
133    pub fn hit_test_centerline(
134        &self,
135        sample: crate::input::PointerSample,
136        radius: f32,
137    ) -> Result<bool, ScreenPolylineError> {
138        if !radius.is_finite() || radius < 0.0 {
139            return Err(ScreenPolylineError::InvalidPickRadius);
140        }
141        if !self.clip.contains_pointer(sample) {
142            return Ok(false);
143        }
144        let p = sample.position().to_vec2();
145        Ok(self.points.windows(2).any(|pair| {
146            let a = pair[0].to_vec2();
147            let b = pair[1].to_vec2();
148            let dx = f64::from(b.x()) - f64::from(a.x());
149            let dy = f64::from(b.y()) - f64::from(a.y());
150            let px = f64::from(p.x()) - f64::from(a.x());
151            let py = f64::from(p.y()) - f64::from(a.y());
152            let t = ((px * dx + py * dy) / (dx * dx + dy * dy)).clamp(0.0, 1.0);
153            (px - t * dx).hypot(py - t * dy) <= f64::from(radius)
154        }))
155    }
156    pub(crate) fn append(&self, scene: &mut ScreenScene) -> Result<(), SceneError> {
157        if !apply_clip(scene, self.clip)? {
158            return Ok(());
159        }
160        scene.try_styled_polyline_on_layer(self.layer, self.points(), *self.style)
161    }
162}
163
164fn validate(
165    points: &[LogicalScreenPosition],
166    style: StrokeStyle2d,
167    limit: usize,
168) -> Result<(), ScreenPolylineError> {
169    if limit < 2 || points.len() > limit {
170        return Err(ScreenPolylineError::PointLimit {
171            limit,
172            requested: points.len(),
173        });
174    }
175    if points.len() >= 2 && points.first() == points.last() {
176        return Err(ScreenPolylineError::ClosedPathUnsupported);
177    }
178    // Engine validates turns, dashes, marker constraints and logical width.
179    // Its temporary conversion is fallible; no approximate validator in Logic.
180    let mut probe = ScreenScene::new(Color::TRANSPARENT).map_err(ScreenPolylineError::Geometry)?;
181    probe
182        .try_styled_polyline(points, style)
183        .map_err(ScreenPolylineError::Geometry)
184}
185fn copy_points(
186    points: &[LogicalScreenPosition],
187) -> Result<Arc<Vec<LogicalScreenPosition>>, ScreenPolylineError> {
188    let mut owned = Vec::new();
189    owned
190        .try_reserve_exact(points.len())
191        .map_err(|_| ScreenPolylineError::Allocation {
192            requested_bytes: points
193                .len()
194                .saturating_mul(size_of::<LogicalScreenPosition>()),
195        })?;
196    owned.extend_from_slice(points);
197    Ok(Arc::new(owned))
198}
199
200/// A rejected path constructor/setter leaves existing visual state intact.
201#[derive(Debug)]
202pub enum ScreenPolylineError {
203    /// Requested count exceeds the ceiling, or the ceiling is below two.
204    PointLimit {
205        /// Per-path point ceiling.
206        limit: usize,
207        /// Requested point count.
208        requested: usize,
209    },
210    /// Engine 0.4.2 cannot join a closed seam without endpoint overlap.
211    ClosedPathUnsupported,
212    /// Exact Engine geometry/style rejection, including unsupported width units.
213    Geometry(SceneError),
214    /// The owned point buffer could not be reserved.
215    Allocation {
216        /// Minimum requested point-buffer bytes.
217        requested_bytes: usize,
218    },
219    /// Selection radius must be finite and nonnegative.
220    InvalidPickRadius,
221}
222impl fmt::Display for ScreenPolylineError {
223    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224        match self {
225            Self::PointLimit { limit, requested } => write!(
226                f,
227                "screen path requests {requested} points with limit {limit} (minimum limit: 2)"
228            ),
229            Self::ClosedPathUnsupported => {
230                f.write_str("closed styled screen paths require an Engine closed-path API")
231            }
232            Self::Geometry(error) => write!(f, "screen path: {error}"),
233            Self::Allocation { requested_bytes } => {
234                write!(f, "screen path could not reserve {requested_bytes} bytes")
235            }
236            Self::InvalidPickRadius => {
237                f.write_str("path picking radius must be finite and nonnegative")
238            }
239        }
240    }
241}
242impl Error for ScreenPolylineError {
243    fn source(&self) -> Option<&(dyn Error + 'static)> {
244        match self {
245            Self::Geometry(error) => Some(error),
246            _ => None,
247        }
248    }
249}