sim_logic/rendering/screen/
rectangle.rs1use super::{ScreenClip, ScreenRectangleVisual, ScreenVisualError, validate_color};
2use sim_engine::{LogicalPixels, SceneError, ScreenScene, ShapeStyle, Stroke};
3
4impl ScreenRectangleVisual {
5 pub fn rounded(
8 position: sim_engine::LogicalScreenPosition,
9 size: sim_engine::LogicalScreenVector,
10 color: sim_engine::Color,
11 radius: f32,
12 ) -> Result<Self, ScreenVisualError> {
13 let mut visual = Self::new(position, size, color)?;
14 visual.set_corner_radius(radius)?;
15 Ok(visual)
16 }
17
18 pub const fn corner_radius(&self) -> f32 {
20 self.corner_radius
21 }
22
23 pub fn set_corner_radius(&mut self, radius: f32) -> Result<(), ScreenVisualError> {
25 if !radius.is_finite() || radius < 0.0 {
26 return Err(ScreenVisualError::InvalidRadius { value: radius });
27 }
28 self.corner_radius = radius;
29 Ok(())
30 }
31
32 pub const fn stroke(&self) -> Option<Stroke> {
34 self.stroke
35 }
36
37 pub fn set_stroke(&mut self, stroke: Option<Stroke>) -> Result<(), ScreenVisualError> {
40 if let Some(stroke) = stroke {
41 validate_stroke(stroke)?;
42 }
43 self.stroke = stroke;
44 Ok(())
45 }
46
47 pub const fn clip(&self) -> ScreenClip {
49 self.clip
50 }
51
52 pub fn set_clip(&mut self, clip: ScreenClip) {
54 self.clip = clip;
55 }
56
57 pub(crate) fn append(&self, scene: &mut ScreenScene) -> Result<(), SceneError> {
58 let clip = match self.clip {
59 ScreenClip::Empty => return Ok(()),
60 ScreenClip::Unclipped => None,
61 ScreenClip::Rectangle(clip) => Some(clip),
62 };
63 scene.set_screen_clip(clip)?;
64 let style = match self.stroke {
65 Some(stroke) => ShapeStyle::fill_stroke(self.color, stroke.width(), stroke.color()),
66 None => ShapeStyle::filled(self.color),
67 };
68 if self.corner_radius == 0.0 {
69 scene.try_square_rect_on_layer(self.layer, self.position, self.size, style)
70 } else {
71 let radius = LogicalPixels::new(self.corner_radius)
72 .map_err(|_| SceneError::InvalidDimension(sim_engine::ScenePrimitive::Rect))?;
73 scene.try_rect_on_layer(self.layer, self.position, self.size, radius, style)
74 }
75 }
76}
77
78pub(super) fn validate_stroke(stroke: Stroke) -> Result<(), ScreenVisualError> {
79 if !stroke.width().is_finite() || stroke.width() <= 0.0 {
80 return Err(ScreenVisualError::InvalidStrokeWidth {
81 value: stroke.width(),
82 });
83 }
84 validate_color(stroke.color())
85}