1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum StrokeWidthMode2d {
15 LogicalPixels,
17 WorldUnits,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum StrokeCap2d {
24 Butt,
26 Square,
28 Round,
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum StrokeJoin2d {
35 Bevel,
37 Round,
39 Miter,
42}
43
44#[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 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 pub fn lengths(&self) -> &[f32] {
95 &self.lengths[..usize::from(self.length_count)]
96 }
97
98 pub const fn phase(self) -> f32 {
100 self.phase
101 }
102
103 pub const fn max_subsegments(self) -> usize {
105 self.max_subsegments
106 }
107}
108
109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub enum StrokeMarkerAnchor2d {
112 BaseAtEndpoint,
114 TipAtEndpoint,
123}
124
125#[derive(Debug, Clone, Copy, PartialEq)]
134pub struct StrokeMarker2d {
135 length: LogicalPixels,
136 width: LogicalPixels,
137 anchor: StrokeMarkerAnchor2d,
138}
139
140impl StrokeMarker2d {
141 pub const fn arrow(length: LogicalPixels, width: LogicalPixels) -> Self {
143 Self {
144 length,
145 width,
146 anchor: StrokeMarkerAnchor2d::BaseAtEndpoint,
147 }
148 }
149
150 pub const fn with_anchor(mut self, anchor: StrokeMarkerAnchor2d) -> Self {
153 self.anchor = anchor;
154 self
155 }
156
157 pub const fn anchor(self) -> StrokeMarkerAnchor2d {
159 self.anchor
160 }
161
162 pub const fn length(self) -> LogicalPixels {
164 self.length
165 }
166
167 pub const fn width(self) -> LogicalPixels {
169 self.width
170 }
171}
172
173#[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 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 pub const fn logical(width: LogicalPixels, color: Color) -> Self {
203 Self::new(width.get(), color)
204 }
205
206 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 pub const fn with_cap(mut self, cap: StrokeCap2d) -> Self {
215 self.cap = cap;
216 self
217 }
218
219 pub const fn with_join(mut self, join: StrokeJoin2d) -> Self {
221 self.join = join;
222 self
223 }
224
225 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 pub const fn with_dash_pattern(mut self, dash: StrokeDashPattern2d) -> Self {
236 self.dash = Some(dash);
237 self
238 }
239
240 pub const fn with_start_marker(mut self, marker: StrokeMarker2d) -> Self {
242 self.start_marker = Some(marker);
243 self
244 }
245
246 pub const fn with_end_marker(mut self, marker: StrokeMarker2d) -> Self {
248 self.end_marker = Some(marker);
249 self
250 }
251
252 pub const fn stroke(self) -> Stroke {
254 self.stroke
255 }
256
257 pub const fn width_mode(self) -> StrokeWidthMode2d {
259 self.width_mode
260 }
261
262 pub const fn cap(self) -> StrokeCap2d {
264 self.cap
265 }
266
267 pub const fn join(self) -> StrokeJoin2d {
269 self.join
270 }
271
272 pub const fn miter_limit(self) -> f32 {
274 self.miter_limit
275 }
276
277 pub const fn dash_pattern(self) -> Option<StrokeDashPattern2d> {
279 self.dash
280 }
281
282 pub const fn start_marker(self) -> Option<StrokeMarker2d> {
284 self.start_marker
285 }
286
287 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308pub enum StrokeStyleError {
309 InvalidDashElementCount,
311 InvalidDashLength,
313 InvalidDashPhase,
315 InvalidDashExpansionLimit,
317 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#[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 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 pub const fn fill(self) -> Option<Fill> {
349 self.fill
350 }
351 pub const fn stroke(self) -> Option<Stroke> {
353 self.stroke
354 }
355 pub const fn shadow(self) -> Option<Shadow> {
357 self.shadow
358 }
359 pub fn filled(color: Color) -> Self {
361 Self::filled_with(Fill::Solid(color))
362 }
363
364 pub fn filled_with(fill: Fill) -> Self {
366 Self {
367 fill: Some(fill),
368 stroke: None,
369 shadow: None,
370 }
371 }
372
373 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq)]
433pub enum Fill {
434 Solid(Color),
436 LinearGradient(LinearGradient),
438 RadialGradient(RadialGradient),
440}
441
442impl Fill {
443 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#[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 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 pub const fn start(self) -> Vec2 {
500 self.start
501 }
502 pub const fn end(self) -> Vec2 {
504 self.end
505 }
506 pub const fn start_color(self) -> Color {
508 self.start_color
509 }
510 pub const fn end_color(self) -> Color {
512 self.end_color
513 }
514
515 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#[derive(Debug, Clone, Copy, PartialEq)]
548pub struct RadialGradient {
549 center: Vec2,
551 inner_radius: f32,
553 outer_radius: f32,
555 inner_color: Color,
557 outer_color: Color,
559}
560
561impl RadialGradient {
562 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 pub const fn center(self) -> Vec2 {
594 self.center
595 }
596
597 pub const fn inner_radius(self) -> f32 {
599 self.inner_radius
600 }
601
602 pub const fn outer_radius(self) -> f32 {
604 self.outer_radius
605 }
606
607 pub const fn inner_color(self) -> Color {
609 self.inner_color
610 }
611
612 pub const fn outer_color(self) -> Color {
614 self.outer_color
615 }
616
617 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#[derive(Debug, Clone, Copy, PartialEq)]
655pub struct Stroke {
656 pub(super) width: f32,
657 color: Color,
658}
659
660impl Stroke {
661 pub const fn new(width: f32, color: Color) -> Self {
666 Self { width, color }
667 }
668 pub const fn width(self) -> f32 {
670 self.width
671 }
672 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#[derive(Debug, Clone, Copy, PartialEq)]
683pub struct Shadow {
684 offset: LogicalScreenVector,
685 pub(super) spread: f32,
686 color: Color,
687}
688
689impl Shadow {
690 pub fn new(offset: LogicalScreenVector, spread: f32, color: Color) -> Self {
692 Self {
693 offset,
694 spread,
695 color,
696 }
697 }
698
699 pub const fn offset(self) -> LogicalScreenVector {
701 self.offset
702 }
703 pub const fn spread(self) -> f32 {
705 self.spread
706 }
707 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}