Skip to main content

sim_engine/scene/
styles.rs

1//! Bounded stroke, paint, gradient and shadow values for ordinary scenes.
2
3use std::{error::Error, fmt};
4
5use crate::{Color, Interpolate, LogicalPixels, LogicalScreenVector, Vec2, WorldLength};
6
7use super::{MAX_STROKE_DASH_SUBSEGMENTS, SceneError, ScenePrimitive};
8
9const MAX_DASH_ELEMENTS: usize = 8;
10const MAX_MITER_LIMIT: f32 = 1_000.0;
11
12/// Coordinate space used by a line or polyline stroke width.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum StrokeWidthMode2d {
15    /// Width remains constant in logical screen pixels while the camera zooms.
16    LogicalPixels,
17    /// Width is measured in the same world units as the path coordinates.
18    WorldUnits,
19}
20
21/// Presentation used at an open line or dash endpoint.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum StrokeCap2d {
24    /// Stop exactly at the endpoint.
25    Butt,
26    /// Extend by half the stroke width beyond the endpoint.
27    Square,
28    /// Add a semicircular endpoint.
29    Round,
30}
31
32/// Presentation used where two visible polyline segments meet.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum StrokeJoin2d {
35    /// Connect the two segment corners directly.
36    Bevel,
37    /// Fill the corner with a circular join.
38    Round,
39    /// Extend corner edges to their intersection, bounded by the style's
40    /// miter limit and falling back to a bevel beyond it.
41    Miter,
42}
43
44/// Fixed-size, allocation-free dash pattern in source path-coordinate units.
45///
46/// Values alternate visible and hidden lengths, beginning with a visible
47/// length. The element count must be even and at most eight. `phase` advances
48/// into the repeating pattern in the same path units. `max_subsegments` is a
49/// hard limit on visible pieces generated for one command.
50#[derive(Debug, Clone, Copy, PartialEq)]
51pub struct StrokeDashPattern2d {
52    lengths: [f32; MAX_DASH_ELEMENTS],
53    length_count: u8,
54    pub(super) phase: f32,
55    pub(super) max_subsegments: usize,
56}
57
58impl StrokeDashPattern2d {
59    /// Builds a bounded alternating visible/hidden dash pattern.
60    pub fn new(
61        lengths: &[f32],
62        phase: f32,
63        max_subsegments: usize,
64    ) -> Result<Self, StrokeStyleError> {
65        if lengths.len() < 2
66            || lengths.len() > MAX_DASH_ELEMENTS
67            || !lengths.len().is_multiple_of(2)
68        {
69            return Err(StrokeStyleError::InvalidDashElementCount);
70        }
71        if lengths
72            .iter()
73            .any(|length| !length.is_finite() || *length <= 0.0)
74        {
75            return Err(StrokeStyleError::InvalidDashLength);
76        }
77        if !phase.is_finite() {
78            return Err(StrokeStyleError::InvalidDashPhase);
79        }
80        if max_subsegments == 0 || max_subsegments > MAX_STROKE_DASH_SUBSEGMENTS {
81            return Err(StrokeStyleError::InvalidDashExpansionLimit);
82        }
83        let mut stored = [0.0; MAX_DASH_ELEMENTS];
84        stored[..lengths.len()].copy_from_slice(lengths);
85        Ok(Self {
86            lengths: stored,
87            length_count: lengths.len() as u8,
88            phase,
89            max_subsegments,
90        })
91    }
92
93    /// Returns the alternating visible/hidden lengths in path units.
94    pub fn lengths(&self) -> &[f32] {
95        &self.lengths[..usize::from(self.length_count)]
96    }
97
98    /// Returns the repeating-pattern phase in path units.
99    pub const fn phase(self) -> f32 {
100        self.phase
101    }
102
103    /// Returns the hard visible-subsegment expansion limit.
104    pub const fn max_subsegments(self) -> usize {
105        self.max_subsegments
106    }
107}
108
109/// Placement of a logical-pixel arrow relative to its mathematical path endpoint.
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub enum StrokeMarkerAnchor2d {
112    /// Put the marker base at the endpoint and extend its tip outward.
113    BaseAtEndpoint,
114    /// Put the marker tip exactly at the endpoint and shorten the shaft inward.
115    ///
116    /// Supported on undashed two-point paths only. Both shaft ends use butt
117    /// boundaries. Each inward length is bounded to one quarter of the projected
118    /// segment's larger absolute X/Y span, preserving a non-inverted shaft even
119    /// with two markers. Marker width stays in logical pixels. World-width shaft
120    /// boundaries are perpendicular to the projected tangent, keeping their
121    /// projected perpendicular thickness without shear into the arrowhead.
122    TipAtEndpoint,
123}
124
125/// Reusable arrow marker definition for a line endpoint.
126///
127/// Marker dimensions are logical pixels even when the line body uses a world
128/// width, keeping scientific annotations readable under camera zoom. By default,
129/// a marked endpoint ignores the ordinary cap: the body ends with a butt boundary at
130/// the path endpoint, which is also the marker base. The filled triangle grows
131/// outward from the path, so markers remain interior-disjoint from arbitrarily
132/// short, dashed, or camera-scaled terminal segments.
133#[derive(Debug, Clone, Copy, PartialEq)]
134pub struct StrokeMarker2d {
135    length: LogicalPixels,
136    width: LogicalPixels,
137    anchor: StrokeMarkerAnchor2d,
138}
139
140impl StrokeMarker2d {
141    /// Builds a filled triangular arrow marker.
142    pub const fn arrow(length: LogicalPixels, width: LogicalPixels) -> Self {
143        Self {
144            length,
145            width,
146            anchor: StrokeMarkerAnchor2d::BaseAtEndpoint,
147        }
148    }
149
150    /// Selects the marker anchor. Tip anchoring uses the bounded exact-vector
151    /// contract documented by [`StrokeMarkerAnchor2d::TipAtEndpoint`].
152    pub const fn with_anchor(mut self, anchor: StrokeMarkerAnchor2d) -> Self {
153        self.anchor = anchor;
154        self
155    }
156
157    /// Returns how the marker is anchored to the mathematical endpoint.
158    pub const fn anchor(self) -> StrokeMarkerAnchor2d {
159        self.anchor
160    }
161
162    /// Returns marker length along the endpoint tangent.
163    pub const fn length(self) -> LogicalPixels {
164        self.length
165    }
166
167    /// Returns full marker width perpendicular to the endpoint tangent.
168    pub const fn width(self) -> LogicalPixels {
169        self.width
170    }
171}
172
173/// Complete bounded styling for open 2D lines and polylines.
174#[derive(Debug, Clone, Copy, PartialEq)]
175pub struct StrokeStyle2d {
176    pub(super) stroke: Stroke,
177    pub(super) width_mode: StrokeWidthMode2d,
178    pub(super) cap: StrokeCap2d,
179    pub(super) join: StrokeJoin2d,
180    pub(super) miter_limit: f32,
181    pub(super) dash: Option<StrokeDashPattern2d>,
182    pub(super) start_marker: Option<StrokeMarker2d>,
183    pub(super) end_marker: Option<StrokeMarker2d>,
184}
185
186impl StrokeStyle2d {
187    /// Builds the legacy logical-pixel round-cap joined-strip style.
188    pub const fn new(width: f32, color: Color) -> Self {
189        Self {
190            stroke: Stroke::new(width, color),
191            width_mode: StrokeWidthMode2d::LogicalPixels,
192            cap: StrokeCap2d::Round,
193            join: StrokeJoin2d::Miter,
194            miter_limit: MAX_MITER_LIMIT,
195            dash: None,
196            start_marker: None,
197            end_marker: None,
198        }
199    }
200
201    /// Builds a validated logical-pixel-width style.
202    pub const fn logical(width: LogicalPixels, color: Color) -> Self {
203        Self::new(width.get(), color)
204    }
205
206    /// Builds a validated world-unit-width style.
207    pub const fn world(width: WorldLength, color: Color) -> Self {
208        let mut style = Self::new(width.get(), color);
209        style.width_mode = StrokeWidthMode2d::WorldUnits;
210        style
211    }
212
213    /// Selects the open endpoint presentation.
214    pub const fn with_cap(mut self, cap: StrokeCap2d) -> Self {
215        self.cap = cap;
216        self
217    }
218
219    /// Selects the connected-segment presentation.
220    pub const fn with_join(mut self, join: StrokeJoin2d) -> Self {
221        self.join = join;
222        self
223    }
224
225    /// Sets the miter-length multiple in `1.0..=1000.0`.
226    pub fn with_miter_limit(mut self, limit: f32) -> Result<Self, StrokeStyleError> {
227        if !limit.is_finite() || !(1.0..=MAX_MITER_LIMIT).contains(&limit) {
228            return Err(StrokeStyleError::InvalidMiterLimit);
229        }
230        self.miter_limit = limit;
231        Ok(self)
232    }
233
234    /// Applies an allocation-free bounded dash pattern.
235    pub const fn with_dash_pattern(mut self, dash: StrokeDashPattern2d) -> Self {
236        self.dash = Some(dash);
237        self
238    }
239
240    /// Adds a triangular marker at the first path point using its selected anchor.
241    pub const fn with_start_marker(mut self, marker: StrokeMarker2d) -> Self {
242        self.start_marker = Some(marker);
243        self
244    }
245
246    /// Adds a triangular marker at the last path point using its selected anchor.
247    pub const fn with_end_marker(mut self, marker: StrokeMarker2d) -> Self {
248        self.end_marker = Some(marker);
249        self
250    }
251
252    /// Returns color and scalar width.
253    pub const fn stroke(self) -> Stroke {
254        self.stroke
255    }
256
257    /// Returns whether width is logical-screen or world-space.
258    pub const fn width_mode(self) -> StrokeWidthMode2d {
259        self.width_mode
260    }
261
262    /// Returns endpoint presentation.
263    pub const fn cap(self) -> StrokeCap2d {
264        self.cap
265    }
266
267    /// Returns connected-segment presentation.
268    pub const fn join(self) -> StrokeJoin2d {
269        self.join
270    }
271
272    /// Returns the bounded miter multiple.
273    pub const fn miter_limit(self) -> f32 {
274        self.miter_limit
275    }
276
277    /// Returns the optional bounded dash pattern.
278    pub const fn dash_pattern(self) -> Option<StrokeDashPattern2d> {
279        self.dash
280    }
281
282    /// Returns the optional first-endpoint marker.
283    pub const fn start_marker(self) -> Option<StrokeMarker2d> {
284        self.start_marker
285    }
286
287    /// Returns the optional last-endpoint marker.
288    pub const fn end_marker(self) -> Option<StrokeMarker2d> {
289        self.end_marker
290    }
291
292    pub(crate) fn has_tip_marker(self) -> bool {
293        [self.start_marker, self.end_marker]
294            .into_iter()
295            .flatten()
296            .any(|marker| marker.anchor == StrokeMarkerAnchor2d::TipAtEndpoint)
297    }
298
299    pub(super) fn is_valid(self) -> bool {
300        self.stroke.is_valid()
301            && self.miter_limit.is_finite()
302            && (1.0..=MAX_MITER_LIMIT).contains(&self.miter_limit)
303    }
304}
305
306/// Invalid bounded line-style configuration.
307#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308pub enum StrokeStyleError {
309    /// Dash patterns require an even count from two through eight.
310    InvalidDashElementCount,
311    /// Every dash and gap length must be positive and finite.
312    InvalidDashLength,
313    /// Dash phase must be finite.
314    InvalidDashPhase,
315    /// Dash expansion limit must be in `1..=1_000_000`.
316    InvalidDashExpansionLimit,
317    /// Miter limit must be finite and in `1.0..=1000.0`.
318    InvalidMiterLimit,
319}
320
321impl fmt::Display for StrokeStyleError {
322    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
323        write!(formatter, "invalid bounded 2D stroke style: {self:?}")
324    }
325}
326
327impl Error for StrokeStyleError {}
328
329/// Fill, stroke, and shadow styling for solid primitives.
330#[derive(Debug, Clone, Copy, PartialEq)]
331pub struct ShapeStyle {
332    pub(super) fill: Option<Fill>,
333    pub(super) stroke: Option<Stroke>,
334    pub(super) shadow: Option<Shadow>,
335}
336
337impl ShapeStyle {
338    /// Builds explicit fill, stroke, and shadow choices.
339    pub const fn new(fill: Option<Fill>, stroke: Option<Stroke>, shadow: Option<Shadow>) -> Self {
340        Self {
341            fill,
342            stroke,
343            shadow,
344        }
345    }
346
347    /// Returns fill paint, if any.
348    pub const fn fill(self) -> Option<Fill> {
349        self.fill
350    }
351    /// Returns outline stroke, if any.
352    pub const fn stroke(self) -> Option<Stroke> {
353        self.stroke
354    }
355    /// Returns shadow styling, if any.
356    pub const fn shadow(self) -> Option<Shadow> {
357        self.shadow
358    }
359    /// Creates a style with fill color only.
360    pub fn filled(color: Color) -> Self {
361        Self::filled_with(Fill::Solid(color))
362    }
363
364    /// Creates a style with fill paint only.
365    pub fn filled_with(fill: Fill) -> Self {
366        Self {
367            fill: Some(fill),
368            stroke: None,
369            shadow: None,
370        }
371    }
372
373    /// Creates a style with stroke only.
374    ///
375    /// `width` is in logical screen pixels.
376    pub fn stroked(width: f32, color: Color) -> Self {
377        Self {
378            fill: None,
379            stroke: Some(Stroke { width, color }),
380            shadow: None,
381        }
382    }
383
384    /// Creates a style with both fill and stroke.
385    ///
386    /// `stroke_width` is in logical screen pixels.
387    pub fn fill_stroke(fill: Color, stroke_width: f32, stroke: Color) -> Self {
388        Self::fill_stroke_with(Fill::Solid(fill), stroke_width, stroke)
389    }
390
391    /// Creates a style with both fill paint and stroke.
392    ///
393    /// `stroke_width` is in logical screen pixels.
394    pub fn fill_stroke_with(fill: Fill, stroke_width: f32, stroke: Color) -> Self {
395        Self {
396            fill: Some(fill),
397            stroke: Some(Stroke {
398                width: stroke_width,
399                color: stroke,
400            }),
401            shadow: None,
402        }
403    }
404
405    /// Adds a shadow to the style.
406    pub fn with_shadow(mut self, shadow: Shadow) -> Self {
407        self.shadow = Some(shadow);
408        self
409    }
410
411    pub(super) fn validate(self, primitive: ScenePrimitive) -> Result<(), SceneError> {
412        if self.fill.is_none() && self.stroke.is_none() && self.shadow.is_none() {
413            return Err(SceneError::MissingStyle(primitive));
414        }
415        if self.fill.is_some_and(|fill| !fill.is_valid()) {
416            return Err(SceneError::InvalidFill(primitive));
417        }
418        if self.stroke.is_some_and(|stroke| !stroke.is_valid()) {
419            return Err(SceneError::InvalidStroke(primitive));
420        }
421        if self.shadow.is_some_and(|shadow| !shadow.is_valid()) {
422            return Err(SceneError::InvalidShadow(primitive));
423        }
424        Ok(())
425    }
426}
427
428/// Paint used to fill a shape.
429///
430/// Gradient coordinates are in world units. Renderers may approximate gradients
431/// per vertex until a more advanced shader path exists.
432#[derive(Debug, Clone, Copy, PartialEq)]
433pub enum Fill {
434    /// Single color over the whole shape.
435    Solid(Color),
436    /// Color interpolation along a world-space axis.
437    LinearGradient(LinearGradient),
438    /// Color interpolation outward from a world-space center.
439    RadialGradient(RadialGradient),
440}
441
442impl Fill {
443    /// Returns the color at a world-space point.
444    ///
445    /// Degenerate gradients fall back to their end color rather than producing
446    /// NaN.
447    pub fn color_at(self, world: Vec2) -> Color {
448        self.color_at_with_offset(world, Vec2::ZERO)
449    }
450
451    pub(crate) fn color_at_with_offset(self, world_base: Vec2, world_offset: Vec2) -> Color {
452        match self {
453            Self::Solid(color) => color,
454            Self::LinearGradient(gradient) => {
455                gradient.color_at_with_offset(world_base, world_offset)
456            }
457            Self::RadialGradient(gradient) => {
458                gradient.color_at_with_offset(world_base, world_offset)
459            }
460        }
461    }
462
463    fn is_valid(self) -> bool {
464        match self {
465            Self::Solid(color) => color.is_normalized(),
466            Self::LinearGradient(gradient) => gradient.is_valid(),
467            Self::RadialGradient(gradient) => gradient.is_valid(),
468        }
469    }
470}
471
472impl From<Color> for Fill {
473    fn from(color: Color) -> Self {
474        Self::Solid(color)
475    }
476}
477
478/// Linear color gradient in world coordinates.
479#[derive(Debug, Clone, Copy, PartialEq)]
480pub struct LinearGradient {
481    start: Vec2,
482    end: Vec2,
483    start_color: Color,
484    end_color: Color,
485}
486
487impl LinearGradient {
488    /// Builds a linear gradient between two world-space points.
489    pub fn new(start: Vec2, end: Vec2, start_color: Color, end_color: Color) -> Self {
490        Self {
491            start,
492            end,
493            start_color,
494            end_color,
495        }
496    }
497
498    /// Returns the world-space gradient start.
499    pub const fn start(self) -> Vec2 {
500        self.start
501    }
502    /// Returns the world-space gradient end.
503    pub const fn end(self) -> Vec2 {
504        self.end
505    }
506    /// Returns the color at the start.
507    pub const fn start_color(self) -> Color {
508        self.start_color
509    }
510    /// Returns the color at the end.
511    pub const fn end_color(self) -> Color {
512        self.end_color
513    }
514
515    /// Samples the gradient at a world-space point.
516    pub fn color_at(self, world: Vec2) -> Color {
517        self.color_at_with_offset(world, Vec2::ZERO)
518    }
519
520    fn color_at_with_offset(self, world_base: Vec2, world_offset: Vec2) -> Color {
521        if !self.is_valid() || !world_base.is_finite() || !world_offset.is_finite() {
522            return self.end_color.clamp();
523        }
524
525        let axis_x = f64::from(self.end.x) - f64::from(self.start.x);
526        let axis_y = f64::from(self.end.y) - f64::from(self.start.y);
527        let relative_x =
528            f64::from(world_base.x) - f64::from(self.start.x) + f64::from(world_offset.x);
529        let relative_y =
530            f64::from(world_base.y) - f64::from(self.start.y) + f64::from(world_offset.y);
531        let axis_length_squared = axis_x * axis_x + axis_y * axis_y;
532        let amount = ((relative_x * axis_x + relative_y * axis_y) / axis_length_squared)
533            .clamp(0.0, 1.0) as f32;
534        self.start_color.interpolate(self.end_color, amount)
535    }
536
537    fn is_valid(self) -> bool {
538        self.start.is_finite()
539            && self.end.is_finite()
540            && self.start_color.is_normalized()
541            && self.end_color.is_normalized()
542            && self.start != self.end
543    }
544}
545
546/// Radial color gradient in world coordinates.
547#[derive(Debug, Clone, Copy, PartialEq)]
548pub struct RadialGradient {
549    /// Center point in world coordinates.
550    center: Vec2,
551    /// Radius where `inner_color` is reached, in world units.
552    inner_radius: f32,
553    /// Radius where `outer_color` is reached, in world units.
554    outer_radius: f32,
555    /// Color at or inside `inner_radius`.
556    inner_color: Color,
557    /// Color at or outside `outer_radius`.
558    outer_color: Color,
559}
560
561impl RadialGradient {
562    /// Builds a radial gradient in world coordinates.
563    ///
564    /// Reversed finite radii are normalized together with their colors so the
565    /// color attached to each radius remains stable.
566    pub fn new(
567        center: Vec2,
568        inner_radius: f32,
569        outer_radius: f32,
570        inner_color: Color,
571        outer_color: Color,
572    ) -> Self {
573        if inner_radius.is_finite() && outer_radius.is_finite() && inner_radius > outer_radius {
574            Self {
575                center,
576                inner_radius: outer_radius,
577                outer_radius: inner_radius,
578                inner_color: outer_color,
579                outer_color: inner_color,
580            }
581        } else {
582            Self {
583                center,
584                inner_radius,
585                outer_radius,
586                inner_color,
587                outer_color,
588            }
589        }
590    }
591
592    /// Returns the world-space gradient center.
593    pub const fn center(self) -> Vec2 {
594        self.center
595    }
596
597    /// Returns the inner radius in world units.
598    pub const fn inner_radius(self) -> f32 {
599        self.inner_radius
600    }
601
602    /// Returns the outer radius in world units.
603    pub const fn outer_radius(self) -> f32 {
604        self.outer_radius
605    }
606
607    /// Returns the inner linear color.
608    pub const fn inner_color(self) -> Color {
609        self.inner_color
610    }
611
612    /// Returns the outer linear color.
613    pub const fn outer_color(self) -> Color {
614        self.outer_color
615    }
616
617    /// Samples the gradient at a world-space point.
618    pub fn color_at(self, world: Vec2) -> Color {
619        self.color_at_with_offset(world, Vec2::ZERO)
620    }
621
622    fn color_at_with_offset(self, world_base: Vec2, world_offset: Vec2) -> Color {
623        if !self.is_valid() || !world_base.is_finite() || !world_offset.is_finite() {
624            return self.outer_color.clamp();
625        }
626
627        let radius_range = self.outer_radius - self.inner_radius;
628        if radius_range == 0.0 {
629            return self.outer_color;
630        }
631
632        let horizontal =
633            f64::from(world_base.x) - f64::from(self.center.x) + f64::from(world_offset.x);
634        let vertical =
635            f64::from(world_base.y) - f64::from(self.center.y) + f64::from(world_offset.y);
636        let distance = horizontal.hypot(vertical);
637        let amount = ((distance - f64::from(self.inner_radius)) / f64::from(radius_range))
638            .clamp(0.0, 1.0) as f32;
639        self.inner_color.interpolate(self.outer_color, amount)
640    }
641
642    fn is_valid(self) -> bool {
643        self.center.is_finite()
644            && self.inner_radius.is_finite()
645            && self.outer_radius.is_finite()
646            && self.inner_radius >= 0.0
647            && self.outer_radius >= self.inner_radius
648            && self.inner_color.is_normalized()
649            && self.outer_color.is_normalized()
650    }
651}
652
653/// Stroke color and width for lines and shape outlines.
654#[derive(Debug, Clone, Copy, PartialEq)]
655pub struct Stroke {
656    pub(super) width: f32,
657    color: Color,
658}
659
660impl Stroke {
661    /// Builds a stroke used by shape outlines and legacy logical-width lines.
662    ///
663    /// [`StrokeStyle2d::world`] reuses the same scalar/color value while making
664    /// the width's coordinate space explicit on the containing style.
665    pub const fn new(width: f32, color: Color) -> Self {
666        Self { width, color }
667    }
668    /// Returns scalar width in the coordinate space selected by its owner.
669    pub const fn width(self) -> f32 {
670        self.width
671    }
672    /// Returns the stroke color.
673    pub const fn color(self) -> Color {
674        self.color
675    }
676    fn is_valid(self) -> bool {
677        self.width.is_finite() && self.width > 0.0 && self.color.is_normalized()
678    }
679}
680
681/// Simple screen-space shadow used by the first renderer slice.
682#[derive(Debug, Clone, Copy, PartialEq)]
683pub struct Shadow {
684    offset: LogicalScreenVector,
685    pub(super) spread: f32,
686    color: Color,
687}
688
689impl Shadow {
690    /// Builds a shadow from logical screen-space offset, spread, and color.
691    pub fn new(offset: LogicalScreenVector, spread: f32, color: Color) -> Self {
692        Self {
693            offset,
694            spread,
695            color,
696        }
697    }
698
699    /// Returns the logical-pixel shadow offset.
700    pub const fn offset(self) -> LogicalScreenVector {
701        self.offset
702    }
703    /// Returns extra logical-pixel spread.
704    pub const fn spread(self) -> f32 {
705        self.spread
706    }
707    /// Returns the shadow color.
708    pub const fn color(self) -> Color {
709        self.color
710    }
711
712    fn is_valid(self) -> bool {
713        self.offset.is_finite()
714            && self.spread.is_finite()
715            && self.spread >= 0.0
716            && (self.spread * 2.0).is_finite()
717            && self.color.is_normalized()
718    }
719}