1use std::{
2 error::Error,
3 fmt,
4 panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
5};
6
7use crate::{Color, Interpolate, LogicalScreenPosition, LogicalScreenVector, Rect, Vec2};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum ScenePrimitive {
12 Circle,
14 Rect,
16 Line,
18 Polyline,
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum SceneError {
25 InvalidBackground,
27 NonFiniteGeometry(ScenePrimitive),
29 InvalidDimension(ScenePrimitive),
31 DegenerateGeometry(ScenePrimitive),
33 MissingStyle(ScenePrimitive),
35 InvalidFill(ScenePrimitive),
37 InvalidStroke(ScenePrimitive),
39 InvalidShadow(ScenePrimitive),
41 InvalidScreenClip,
43 NonFiniteDepth,
45}
46
47impl fmt::Display for SceneError {
48 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
49 write!(formatter, "scene command rejected: {self:?}")
50 }
51}
52
53impl Error for SceneError {}
54
55#[derive(Debug, Clone)]
60pub struct Scene {
61 background: Color,
62 commands: Vec<SceneCommand>,
64 next_order: u64,
65 current_screen_clip: Option<ScreenClipRect>,
66 current_depth: f32,
67}
68
69impl Scene {
70 pub fn new(background: Color) -> Result<Self, SceneError> {
72 if !background.is_normalized() {
73 return Err(SceneError::InvalidBackground);
74 }
75 Ok(Self {
76 background,
77 commands: Vec::new(),
78 next_order: 0,
79 current_screen_clip: None,
80 current_depth: 0.0,
81 })
82 }
83
84 pub fn background(&self) -> Color {
86 self.background
87 }
88
89 pub fn set_background(&mut self, background: Color) -> Result<(), SceneError> {
91 if !background.is_normalized() {
92 return Err(SceneError::InvalidBackground);
93 }
94 self.background = background;
95 Ok(())
96 }
97
98 pub fn clear(&mut self) {
100 self.commands.clear();
101 self.next_order = 0;
102 self.current_screen_clip = None;
103 self.current_depth = 0.0;
104 }
105
106 pub fn commands(&self) -> &[SceneCommand] {
108 &self.commands
109 }
110
111 pub fn command_count(&self) -> usize {
113 self.commands.len()
114 }
115
116 pub fn set_screen_clip(
125 &mut self,
126 screen_clip: Option<ScreenClipRect>,
127 ) -> Result<Option<ScreenClipRect>, SceneError> {
128 if screen_clip.is_some_and(|clip| !clip.is_valid()) {
129 return Err(SceneError::InvalidScreenClip);
130 }
131 Ok(std::mem::replace(
132 &mut self.current_screen_clip,
133 screen_clip,
134 ))
135 }
136
137 pub fn with_screen_clip<R>(
143 &mut self,
144 screen_clip: ScreenClipRect,
145 draw: impl FnOnce(&mut Self) -> R,
146 ) -> Result<R, SceneError> {
147 if !screen_clip.is_valid() {
148 return Err(SceneError::InvalidScreenClip);
149 }
150 let previous = self.current_screen_clip;
151 let combined = match previous {
152 Some(outer) => outer.intersection(screen_clip)?,
153 None => screen_clip,
154 };
155 if !combined.is_valid() {
156 return Err(SceneError::InvalidScreenClip);
157 }
158 self.current_screen_clip = Some(combined);
159 let result = catch_unwind(AssertUnwindSafe(|| draw(self)));
160 self.current_screen_clip = previous;
161 match result {
162 Ok(result) => Ok(result),
163 Err(payload) => resume_unwind(payload),
164 }
165 }
166
167 pub fn set_depth(&mut self, depth: f32) -> bool {
173 self.try_set_depth(depth).is_ok()
174 }
175
176 pub fn try_set_depth(&mut self, depth: f32) -> Result<(), SceneError> {
178 if !depth.is_finite() {
179 return Err(SceneError::NonFiniteDepth);
180 }
181 self.current_depth = depth;
182 Ok(())
183 }
184
185 pub fn with_depth<R>(
190 &mut self,
191 depth: f32,
192 draw: impl FnOnce(&mut Self) -> R,
193 ) -> Result<R, SceneError> {
194 if !depth.is_finite() {
195 return Err(SceneError::NonFiniteDepth);
196 }
197
198 let previous = self.current_depth;
199 self.current_depth = depth;
200 let result = catch_unwind(AssertUnwindSafe(|| draw(self)));
201 self.current_depth = previous;
202 match result {
203 Ok(result) => Ok(result),
204 Err(payload) => resume_unwind(payload),
205 }
206 }
207
208 pub fn push(&mut self, command: DrawCommand) -> bool {
213 self.try_push(command).is_ok()
214 }
215
216 pub fn try_push(&mut self, command: DrawCommand) -> Result<(), SceneError> {
218 self.try_push_to_layer(Layer::DEFAULT, command)
219 }
220
221 pub fn push_to_layer(&mut self, layer: Layer, command: DrawCommand) -> bool {
227 self.try_push_to_layer(layer, command).is_ok()
228 }
229
230 pub fn try_push_to_layer(
232 &mut self,
233 layer: Layer,
234 command: DrawCommand,
235 ) -> Result<(), SceneError> {
236 command.validate()?;
237 if self
238 .current_screen_clip
239 .is_some_and(|screen_clip| !screen_clip.is_valid())
240 {
241 return Err(SceneError::InvalidScreenClip);
242 }
243
244 let order = self.next_order;
245 self.next_order = self.next_order.saturating_add(1);
246 let scene_command = SceneCommand {
247 layer,
248 order,
249 depth: self.current_depth,
250 screen_clip: self.current_screen_clip,
251 command,
252 };
253 let position = self.commands.partition_point(|existing| {
254 existing.layer < scene_command.layer
255 || (existing.layer == scene_command.layer && existing.order <= scene_command.order)
256 });
257 self.commands.insert(position, scene_command);
258 Ok(())
259 }
260
261 pub fn circle(&mut self, center: Vec2, radius: f32, style: ShapeStyle) -> bool {
266 self.try_circle(center, radius, style).is_ok()
267 }
268
269 pub fn try_circle(
271 &mut self,
272 center: Vec2,
273 radius: f32,
274 style: ShapeStyle,
275 ) -> Result<(), SceneError> {
276 self.try_circle_on_layer(Layer::DEFAULT, center, radius, style)
277 }
278
279 pub fn circle_on_layer(
284 &mut self,
285 layer: Layer,
286 center: Vec2,
287 radius: f32,
288 style: ShapeStyle,
289 ) -> bool {
290 self.try_circle_on_layer(layer, center, radius, style)
291 .is_ok()
292 }
293
294 pub fn try_circle_on_layer(
296 &mut self,
297 layer: Layer,
298 center: Vec2,
299 radius: f32,
300 style: ShapeStyle,
301 ) -> Result<(), SceneError> {
302 self.try_push_to_layer(
303 layer,
304 DrawCommand::Circle(Circle {
305 center,
306 radius,
307 style,
308 }),
309 )
310 }
311
312 pub fn rect(&mut self, rect: Rect, corner_radius: f32, style: ShapeStyle) -> bool {
318 self.try_rect(rect, corner_radius, style).is_ok()
319 }
320
321 pub fn try_rect(
323 &mut self,
324 rect: Rect,
325 corner_radius: f32,
326 style: ShapeStyle,
327 ) -> Result<(), SceneError> {
328 self.try_rect_on_layer(Layer::DEFAULT, rect, corner_radius, style)
329 }
330
331 pub fn rect_on_layer(
337 &mut self,
338 layer: Layer,
339 rect: Rect,
340 corner_radius: f32,
341 style: ShapeStyle,
342 ) -> bool {
343 self.try_rect_on_layer(layer, rect, corner_radius, style)
344 .is_ok()
345 }
346
347 pub fn try_rect_on_layer(
349 &mut self,
350 layer: Layer,
351 rect: Rect,
352 corner_radius: f32,
353 style: ShapeStyle,
354 ) -> Result<(), SceneError> {
355 self.try_push_to_layer(
356 layer,
357 DrawCommand::Rect(RectShape {
358 rect,
359 corner_radius,
360 style,
361 }),
362 )
363 }
364
365 pub fn line(&mut self, from: Vec2, to: Vec2, width: f32, color: Color) -> bool {
371 self.try_line(from, to, width, color).is_ok()
372 }
373
374 pub fn try_line(
376 &mut self,
377 from: Vec2,
378 to: Vec2,
379 width: f32,
380 color: Color,
381 ) -> Result<(), SceneError> {
382 self.try_line_on_layer(Layer::DEFAULT, from, to, width, color)
383 }
384
385 pub fn line_on_layer(
391 &mut self,
392 layer: Layer,
393 from: Vec2,
394 to: Vec2,
395 width: f32,
396 color: Color,
397 ) -> bool {
398 self.try_line_on_layer(layer, from, to, width, color)
399 .is_ok()
400 }
401
402 pub fn try_line_on_layer(
404 &mut self,
405 layer: Layer,
406 from: Vec2,
407 to: Vec2,
408 width: f32,
409 color: Color,
410 ) -> Result<(), SceneError> {
411 self.try_push_to_layer(
412 layer,
413 DrawCommand::Line(Line {
414 from,
415 to,
416 stroke: Stroke { width, color },
417 }),
418 )
419 }
420
421 pub fn polyline(&mut self, points: Vec<Vec2>, width: f32, color: Color) -> bool {
426 self.try_polyline(points, width, color).is_ok()
427 }
428
429 pub fn try_polyline(
431 &mut self,
432 points: Vec<Vec2>,
433 width: f32,
434 color: Color,
435 ) -> Result<(), SceneError> {
436 self.try_polyline_on_layer(Layer::DEFAULT, points, width, color)
437 }
438
439 pub fn polyline_on_layer(
444 &mut self,
445 layer: Layer,
446 points: Vec<Vec2>,
447 width: f32,
448 color: Color,
449 ) -> bool {
450 self.try_polyline_on_layer(layer, points, width, color)
451 .is_ok()
452 }
453
454 pub fn try_polyline_on_layer(
456 &mut self,
457 layer: Layer,
458 points: Vec<Vec2>,
459 width: f32,
460 color: Color,
461 ) -> Result<(), SceneError> {
462 self.try_push_to_layer(
463 layer,
464 DrawCommand::Polyline(Polyline {
465 points,
466 stroke: Stroke { width, color },
467 }),
468 )
469 }
470}
471
472#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
476pub struct Layer {
477 order: i32,
478}
479
480impl Layer {
481 pub const DEFAULT: Self = Self::new(0);
483 pub const BACKGROUND: Self = Self::new(-100);
485 pub const FOREGROUND: Self = Self::new(100);
487
488 pub const fn new(order: i32) -> Self {
490 Self { order }
491 }
492
493 pub const fn order(self) -> i32 {
495 self.order
496 }
497}
498
499#[derive(Debug, Clone, Copy, PartialEq)]
505pub struct ScreenClipRect {
506 rect: Rect,
507}
508
509impl ScreenClipRect {
510 pub fn new(min: LogicalScreenPosition, max: LogicalScreenPosition) -> Result<Self, SceneError> {
512 Self::from_rect(Rect::new(min.to_vec2(), max.to_vec2()))
513 }
514
515 pub fn from_min_size(
519 min: LogicalScreenPosition,
520 size: LogicalScreenVector,
521 ) -> Result<Self, SceneError> {
522 Self::from_rect(Rect::from_min_size(min.to_vec2(), size.to_vec2()))
523 }
524
525 fn from_rect(rect: Rect) -> Result<Self, SceneError> {
526 let clip = Self { rect };
527 clip.is_valid()
528 .then_some(clip)
529 .ok_or(SceneError::InvalidScreenClip)
530 }
531
532 #[cfg(feature = "wgpu")]
533 pub(crate) fn rect(self) -> Rect {
534 self.rect
535 }
536
537 pub fn min(self) -> LogicalScreenPosition {
539 LogicalScreenPosition::from_vec2(self.rect.normalized().min)
540 }
541
542 pub fn max(self) -> LogicalScreenPosition {
544 LogicalScreenPosition::from_vec2(self.rect.normalized().max)
545 }
546
547 pub fn intersection(self, other: Self) -> Result<Self, SceneError> {
551 let first = self.rect.normalized();
552 let second = other.rect.normalized();
553 let min = Vec2::new(first.min.x.max(second.min.x), first.min.y.max(second.min.y));
554 let max = Vec2::new(first.max.x.min(second.max.x), first.max.y.min(second.max.y));
555
556 Self::new(
557 LogicalScreenPosition::from_vec2(min),
558 LogicalScreenPosition::from_vec2(Vec2::new(max.x.max(min.x), max.y.max(min.y))),
559 )
560 }
561
562 fn is_valid(self) -> bool {
563 if !self.rect.min.is_finite() || !self.rect.max.is_finite() {
564 return false;
565 }
566
567 let rect = self.rect.normalized();
568 rect.width() > 0.0 && rect.height() > 0.0
569 }
570}
571
572#[derive(Debug, Clone)]
574pub struct SceneCommand {
575 layer: Layer,
577 order: u64,
579 depth: f32,
581 screen_clip: Option<ScreenClipRect>,
583 command: DrawCommand,
585}
586
587impl SceneCommand {
588 pub fn layer(&self) -> Layer {
590 self.layer
591 }
592
593 pub fn order(&self) -> u64 {
595 self.order
596 }
597
598 pub fn depth(&self) -> f32 {
603 self.depth
604 }
605
606 pub fn screen_clip(&self) -> Option<ScreenClipRect> {
608 self.screen_clip
609 }
610
611 pub fn command(&self) -> &DrawCommand {
613 &self.command
614 }
615}
616
617#[derive(Debug, Clone)]
619#[non_exhaustive]
620pub enum DrawCommand {
621 Circle(Circle),
623 Rect(RectShape),
625 Line(Line),
627 Polyline(Polyline),
629}
630
631impl DrawCommand {
632 fn validate(&self) -> Result<(), SceneError> {
633 match self {
634 Self::Circle(circle) => {
635 if !circle.center.is_finite() {
636 return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Circle));
637 }
638 if !circle.radius.is_finite() || circle.radius <= 0.0 {
639 return Err(SceneError::InvalidDimension(ScenePrimitive::Circle));
640 }
641 if !(circle.center + Vec2::splat(circle.radius)).is_finite()
642 || !(circle.center - Vec2::splat(circle.radius)).is_finite()
643 {
644 return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Circle));
645 }
646 circle.style.validate(ScenePrimitive::Circle)
647 }
648 Self::Rect(rectangle) => {
649 let rect = rectangle.rect.normalized();
650 if !rect.min.is_finite() || !rect.max.is_finite() {
651 return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Rect));
652 }
653 let width = rect.width();
654 let height = rect.height();
655 if !width.is_finite() || !height.is_finite() {
656 return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Rect));
657 }
658 if width <= 0.0
659 || height <= 0.0
660 || !rectangle.corner_radius.is_finite()
661 || rectangle.corner_radius < 0.0
662 {
663 return Err(SceneError::InvalidDimension(ScenePrimitive::Rect));
664 }
665 rectangle.style.validate(ScenePrimitive::Rect)
666 }
667 Self::Line(line) => {
668 if !line.from.is_finite() || !line.to.is_finite() {
669 return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Line));
670 }
671 if !(line.to - line.from).is_finite() {
672 return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Line));
673 }
674 if !drawable_segment(line.from, line.to) {
675 return Err(SceneError::DegenerateGeometry(ScenePrimitive::Line));
676 }
677 if !line.stroke.is_valid() {
678 return Err(SceneError::InvalidStroke(ScenePrimitive::Line));
679 }
680 Ok(())
681 }
682 Self::Polyline(polyline) => {
683 if !polyline.points.iter().all(|point| point.is_finite()) {
684 return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Polyline));
685 }
686 if polyline
687 .points
688 .windows(2)
689 .any(|pair| !(pair[1] - pair[0]).is_finite())
690 {
691 return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Polyline));
692 }
693 if polyline.points.len() < 2
694 || !polyline
695 .points
696 .windows(2)
697 .any(|pair| drawable_segment(pair[0], pair[1]))
698 {
699 return Err(SceneError::DegenerateGeometry(ScenePrimitive::Polyline));
700 }
701 if !polyline.stroke.is_valid() {
702 return Err(SceneError::InvalidStroke(ScenePrimitive::Polyline));
703 }
704 Ok(())
705 }
706 }
707 }
708}
709
710fn drawable_segment(from: Vec2, to: Vec2) -> bool {
711 let delta = to - from;
712 delta.is_finite() && (delta.x != 0.0 || delta.y != 0.0)
713}
714
715#[derive(Debug, Clone)]
717pub struct Circle {
718 center: Vec2,
719 radius: f32,
720 style: ShapeStyle,
721}
722
723impl Circle {
724 pub const fn center(&self) -> Vec2 {
726 self.center
727 }
728 pub const fn radius(&self) -> f32 {
730 self.radius
731 }
732 pub const fn style(&self) -> ShapeStyle {
734 self.style
735 }
736}
737
738#[derive(Debug, Clone)]
740pub struct RectShape {
741 rect: Rect,
742 corner_radius: f32,
743 style: ShapeStyle,
744}
745
746impl RectShape {
747 pub const fn rect(&self) -> Rect {
749 self.rect
750 }
751 pub const fn corner_radius(&self) -> f32 {
753 self.corner_radius
754 }
755 pub const fn style(&self) -> ShapeStyle {
757 self.style
758 }
759}
760
761#[derive(Debug, Clone)]
763pub struct Line {
764 from: Vec2,
765 to: Vec2,
766 stroke: Stroke,
767}
768
769impl Line {
770 pub const fn from(&self) -> Vec2 {
772 self.from
773 }
774 pub const fn to(&self) -> Vec2 {
776 self.to
777 }
778 pub const fn stroke(&self) -> Stroke {
780 self.stroke
781 }
782}
783
784#[derive(Debug, Clone)]
786pub struct Polyline {
787 points: Vec<Vec2>,
788 stroke: Stroke,
789}
790
791impl Polyline {
792 pub fn points(&self) -> &[Vec2] {
794 &self.points
795 }
796 pub const fn stroke(&self) -> Stroke {
798 self.stroke
799 }
800}
801
802#[derive(Debug, Clone, Copy, PartialEq)]
804pub struct ShapeStyle {
805 fill: Option<Fill>,
806 stroke: Option<Stroke>,
807 shadow: Option<Shadow>,
808}
809
810impl ShapeStyle {
811 pub const fn new(fill: Option<Fill>, stroke: Option<Stroke>, shadow: Option<Shadow>) -> Self {
813 Self {
814 fill,
815 stroke,
816 shadow,
817 }
818 }
819
820 pub const fn fill(self) -> Option<Fill> {
822 self.fill
823 }
824 pub const fn stroke(self) -> Option<Stroke> {
826 self.stroke
827 }
828 pub const fn shadow(self) -> Option<Shadow> {
830 self.shadow
831 }
832 pub fn filled(color: Color) -> Self {
834 Self::filled_with(Fill::Solid(color))
835 }
836
837 pub fn filled_with(fill: Fill) -> Self {
839 Self {
840 fill: Some(fill),
841 stroke: None,
842 shadow: None,
843 }
844 }
845
846 pub fn stroked(width: f32, color: Color) -> Self {
850 Self {
851 fill: None,
852 stroke: Some(Stroke { width, color }),
853 shadow: None,
854 }
855 }
856
857 pub fn fill_stroke(fill: Color, stroke_width: f32, stroke: Color) -> Self {
861 Self::fill_stroke_with(Fill::Solid(fill), stroke_width, stroke)
862 }
863
864 pub fn fill_stroke_with(fill: Fill, stroke_width: f32, stroke: Color) -> Self {
868 Self {
869 fill: Some(fill),
870 stroke: Some(Stroke {
871 width: stroke_width,
872 color: stroke,
873 }),
874 shadow: None,
875 }
876 }
877
878 pub fn with_shadow(mut self, shadow: Shadow) -> Self {
880 self.shadow = Some(shadow);
881 self
882 }
883
884 fn validate(self, primitive: ScenePrimitive) -> Result<(), SceneError> {
885 if self.fill.is_none() && self.stroke.is_none() && self.shadow.is_none() {
886 return Err(SceneError::MissingStyle(primitive));
887 }
888 if self.fill.is_some_and(|fill| !fill.is_valid()) {
889 return Err(SceneError::InvalidFill(primitive));
890 }
891 if self.stroke.is_some_and(|stroke| !stroke.is_valid()) {
892 return Err(SceneError::InvalidStroke(primitive));
893 }
894 if self.shadow.is_some_and(|shadow| !shadow.is_valid()) {
895 return Err(SceneError::InvalidShadow(primitive));
896 }
897 Ok(())
898 }
899}
900
901#[derive(Debug, Clone, Copy, PartialEq)]
906pub enum Fill {
907 Solid(Color),
909 LinearGradient(LinearGradient),
911 RadialGradient(RadialGradient),
913}
914
915impl Fill {
916 pub fn color_at(self, world: Vec2) -> Color {
921 match self {
922 Self::Solid(color) => color,
923 Self::LinearGradient(gradient) => gradient.color_at(world),
924 Self::RadialGradient(gradient) => gradient.color_at(world),
925 }
926 }
927
928 fn is_valid(self) -> bool {
929 match self {
930 Self::Solid(color) => color.is_normalized(),
931 Self::LinearGradient(gradient) => gradient.is_valid(),
932 Self::RadialGradient(gradient) => gradient.is_valid(),
933 }
934 }
935}
936
937impl From<Color> for Fill {
938 fn from(color: Color) -> Self {
939 Self::Solid(color)
940 }
941}
942
943#[derive(Debug, Clone, Copy, PartialEq)]
945pub struct LinearGradient {
946 start: Vec2,
947 end: Vec2,
948 start_color: Color,
949 end_color: Color,
950}
951
952impl LinearGradient {
953 pub fn new(start: Vec2, end: Vec2, start_color: Color, end_color: Color) -> Self {
955 Self {
956 start,
957 end,
958 start_color,
959 end_color,
960 }
961 }
962
963 pub const fn start(self) -> Vec2 {
965 self.start
966 }
967 pub const fn end(self) -> Vec2 {
969 self.end
970 }
971 pub const fn start_color(self) -> Color {
973 self.start_color
974 }
975 pub const fn end_color(self) -> Color {
977 self.end_color
978 }
979
980 pub fn color_at(self, world: Vec2) -> Color {
982 if !self.is_valid() || !world.is_finite() {
983 return self.end_color.clamp();
984 }
985
986 let axis_x = f64::from(self.end.x) - f64::from(self.start.x);
987 let axis_y = f64::from(self.end.y) - f64::from(self.start.y);
988 let relative_x = f64::from(world.x) - f64::from(self.start.x);
989 let relative_y = f64::from(world.y) - f64::from(self.start.y);
990 let axis_length_squared = axis_x * axis_x + axis_y * axis_y;
991 let amount = ((relative_x * axis_x + relative_y * axis_y) / axis_length_squared)
992 .clamp(0.0, 1.0) as f32;
993 self.start_color.interpolate(self.end_color, amount)
994 }
995
996 fn is_valid(self) -> bool {
997 self.start.is_finite()
998 && self.end.is_finite()
999 && self.start_color.is_normalized()
1000 && self.end_color.is_normalized()
1001 && self.start != self.end
1002 }
1003}
1004
1005#[derive(Debug, Clone, Copy, PartialEq)]
1007pub struct RadialGradient {
1008 center: Vec2,
1010 inner_radius: f32,
1012 outer_radius: f32,
1014 inner_color: Color,
1016 outer_color: Color,
1018}
1019
1020impl RadialGradient {
1021 pub fn new(
1026 center: Vec2,
1027 inner_radius: f32,
1028 outer_radius: f32,
1029 inner_color: Color,
1030 outer_color: Color,
1031 ) -> Self {
1032 if inner_radius.is_finite() && outer_radius.is_finite() && inner_radius > outer_radius {
1033 Self {
1034 center,
1035 inner_radius: outer_radius,
1036 outer_radius: inner_radius,
1037 inner_color: outer_color,
1038 outer_color: inner_color,
1039 }
1040 } else {
1041 Self {
1042 center,
1043 inner_radius,
1044 outer_radius,
1045 inner_color,
1046 outer_color,
1047 }
1048 }
1049 }
1050
1051 pub const fn center(self) -> Vec2 {
1053 self.center
1054 }
1055
1056 pub const fn inner_radius(self) -> f32 {
1058 self.inner_radius
1059 }
1060
1061 pub const fn outer_radius(self) -> f32 {
1063 self.outer_radius
1064 }
1065
1066 pub const fn inner_color(self) -> Color {
1068 self.inner_color
1069 }
1070
1071 pub const fn outer_color(self) -> Color {
1073 self.outer_color
1074 }
1075
1076 pub fn color_at(self, world: Vec2) -> Color {
1078 if !self.is_valid() || !world.is_finite() {
1079 return self.outer_color.clamp();
1080 }
1081
1082 let radius_range = self.outer_radius - self.inner_radius;
1083 if radius_range.abs() <= f32::EPSILON {
1084 return self.outer_color;
1085 }
1086
1087 let horizontal = f64::from(world.x) - f64::from(self.center.x);
1088 let vertical = f64::from(world.y) - f64::from(self.center.y);
1089 let distance = horizontal.hypot(vertical);
1090 let amount = ((distance - f64::from(self.inner_radius)) / f64::from(radius_range))
1091 .clamp(0.0, 1.0) as f32;
1092 self.inner_color.interpolate(self.outer_color, amount)
1093 }
1094
1095 fn is_valid(self) -> bool {
1096 self.center.is_finite()
1097 && self.inner_radius.is_finite()
1098 && self.outer_radius.is_finite()
1099 && self.inner_radius >= 0.0
1100 && self.outer_radius >= self.inner_radius
1101 && self.inner_color.is_normalized()
1102 && self.outer_color.is_normalized()
1103 }
1104}
1105
1106#[derive(Debug, Clone, Copy, PartialEq)]
1108pub struct Stroke {
1109 width: f32,
1110 color: Color,
1111}
1112
1113impl Stroke {
1114 pub const fn new(width: f32, color: Color) -> Self {
1116 Self { width, color }
1117 }
1118 pub const fn width(self) -> f32 {
1120 self.width
1121 }
1122 pub const fn color(self) -> Color {
1124 self.color
1125 }
1126 fn is_valid(self) -> bool {
1127 self.width.is_finite() && self.width > 0.0 && self.color.is_normalized()
1128 }
1129}
1130
1131#[derive(Debug, Clone, Copy, PartialEq)]
1133pub struct Shadow {
1134 offset: LogicalScreenVector,
1135 spread: f32,
1136 color: Color,
1137}
1138
1139impl Shadow {
1140 pub fn new(offset: LogicalScreenVector, spread: f32, color: Color) -> Self {
1142 Self {
1143 offset,
1144 spread,
1145 color,
1146 }
1147 }
1148
1149 pub const fn offset(self) -> LogicalScreenVector {
1151 self.offset
1152 }
1153 pub const fn spread(self) -> f32 {
1155 self.spread
1156 }
1157 pub const fn color(self) -> Color {
1159 self.color
1160 }
1161
1162 fn is_valid(self) -> bool {
1163 self.offset.is_finite()
1164 && self.spread.is_finite()
1165 && self.spread >= 0.0
1166 && (self.spread * 2.0).is_finite()
1167 && self.color.is_normalized()
1168 }
1169}
1170
1171#[cfg(test)]
1172mod tests {
1173 use std::panic::{AssertUnwindSafe, catch_unwind};
1174
1175 use crate::{
1176 Color, DrawCommand, Fill, Layer, LinearGradient, LogicalScreenPosition,
1177 LogicalScreenVector, RadialGradient, Rect, Scene, SceneError, ScenePrimitive,
1178 ScreenClipRect, ShapeStyle, Vec2,
1179 };
1180
1181 #[test]
1182 fn scene_collects_visual_commands_only() {
1183 let mut scene = Scene::new(Color::BLACK).unwrap();
1184 scene.circle(Vec2::ZERO, 10.0, ShapeStyle::filled(Color::WHITE));
1185
1186 assert_eq!(scene.commands.len(), 1);
1187 }
1188
1189 #[test]
1190 fn scene_keeps_commands_sorted_by_layer() {
1191 let mut scene = Scene::new(Color::BLACK).unwrap();
1192 scene.circle_on_layer(
1193 Layer::FOREGROUND,
1194 Vec2::ZERO,
1195 10.0,
1196 ShapeStyle::filled(Color::WHITE),
1197 );
1198 scene.line_on_layer(Layer::BACKGROUND, Vec2::ZERO, Vec2::X, 1.0, Color::WHITE);
1199
1200 assert!(matches!(scene.commands[0].command, DrawCommand::Line(_)));
1201 assert!(matches!(scene.commands[1].command, DrawCommand::Circle(_)));
1202 }
1203
1204 #[test]
1205 fn linear_gradient_samples_along_axis() {
1206 let gradient = LinearGradient::new(Vec2::ZERO, Vec2::X, Color::BLACK, Color::WHITE);
1207
1208 let sampled = Fill::LinearGradient(gradient).color_at(Vec2::new(0.5, 4.0));
1209
1210 assert!((sampled.red() - 0.5).abs() < 0.001);
1211 assert!((sampled.green() - 0.5).abs() < 0.001);
1212 assert!((sampled.blue() - 0.5).abs() < 0.001);
1213 }
1214
1215 #[test]
1216 fn extreme_gradients_sample_without_f32_overflow() {
1217 let gradient = LinearGradient::new(
1218 Vec2::new(-f32::MAX, 0.0),
1219 Vec2::new(f32::MAX, 0.0),
1220 Color::BLACK,
1221 Color::WHITE,
1222 );
1223 let mut scene = Scene::new(Color::BLACK).unwrap();
1224
1225 assert!(
1226 scene
1227 .try_circle(
1228 Vec2::ZERO,
1229 1.0,
1230 ShapeStyle::filled_with(Fill::LinearGradient(gradient)),
1231 )
1232 .is_ok()
1233 );
1234 assert_eq!(
1235 gradient.color_at(Vec2::ZERO),
1236 Color::rgba(0.5, 0.5, 0.5, 1.0)
1237 );
1238
1239 let radial = RadialGradient::new(
1240 Vec2::splat(f32::MAX),
1241 0.0,
1242 f32::MAX,
1243 Color::BLACK,
1244 Color::WHITE,
1245 );
1246 assert_eq!(radial.color_at(Vec2::splat(-f32::MAX)), Color::WHITE);
1247 }
1248
1249 #[test]
1250 fn overflowing_circle_and_shadow_are_rejected_at_scene_boundary() {
1251 let mut scene = Scene::new(Color::BLACK).unwrap();
1252 assert_eq!(
1253 scene.try_circle(
1254 Vec2::splat(f32::MAX),
1255 f32::MAX,
1256 ShapeStyle::filled(Color::WHITE),
1257 ),
1258 Err(SceneError::NonFiniteGeometry(ScenePrimitive::Circle))
1259 );
1260 assert_eq!(
1261 scene.try_circle(
1262 Vec2::ZERO,
1263 1.0,
1264 ShapeStyle::filled(Color::WHITE).with_shadow(super::Shadow::new(
1265 LogicalScreenVector::new(0.0, 0.0),
1266 f32::MAX,
1267 Color::WHITE,
1268 )),
1269 ),
1270 Err(SceneError::InvalidShadow(ScenePrimitive::Circle))
1271 );
1272 assert_eq!(
1273 scene.try_line(
1274 Vec2::new(-f32::MAX, 0.0),
1275 Vec2::new(f32::MAX, 0.0),
1276 1.0,
1277 Color::WHITE,
1278 ),
1279 Err(SceneError::NonFiniteGeometry(ScenePrimitive::Line))
1280 );
1281 assert_eq!(
1282 scene.try_rect(
1283 Rect::new(Vec2::new(-f32::MAX, 0.0), Vec2::new(f32::MAX, 1.0),),
1284 0.0,
1285 ShapeStyle::filled(Color::WHITE),
1286 ),
1287 Err(SceneError::NonFiniteGeometry(ScenePrimitive::Rect))
1288 );
1289 }
1290
1291 #[test]
1292 fn commands_capture_temporary_screen_clip() {
1293 let mut scene = Scene::new(Color::BLACK).unwrap();
1294 let outer = ScreenClipRect::from_min_size(
1295 LogicalScreenPosition::new(10.0, 20.0),
1296 LogicalScreenVector::new(100.0, 80.0),
1297 )
1298 .unwrap();
1299 let inner = ScreenClipRect::from_min_size(
1300 LogicalScreenPosition::new(50.0, 0.0),
1301 LogicalScreenVector::new(100.0, 50.0),
1302 )
1303 .unwrap();
1304
1305 scene
1306 .with_screen_clip(outer, |scene| {
1307 scene
1308 .with_screen_clip(inner, |scene| {
1309 scene.circle(Vec2::ZERO, 10.0, ShapeStyle::filled(Color::WHITE));
1310 })
1311 .unwrap();
1312 })
1313 .unwrap();
1314 scene.circle(Vec2::ZERO, 10.0, ShapeStyle::filled(Color::WHITE));
1315
1316 assert_eq!(
1317 scene.commands[0].screen_clip,
1318 Some(
1319 ScreenClipRect::new(
1320 LogicalScreenPosition::new(50.0, 20.0),
1321 LogicalScreenPosition::new(110.0, 50.0),
1322 )
1323 .unwrap(),
1324 )
1325 );
1326 assert_eq!(scene.commands[1].screen_clip, None);
1327 }
1328
1329 #[test]
1330 fn scene_rejects_invalid_primitives_before_ordering() {
1331 let mut scene = Scene::new(Color::BLACK).unwrap();
1332
1333 assert!(!scene.circle(Vec2::ZERO, -1.0, ShapeStyle::filled(Color::WHITE)));
1334 assert!(!scene.line(Vec2::ZERO, Vec2::X, f32::NAN, Color::WHITE));
1335 assert!(!scene.polyline(vec![Vec2::ZERO], 1.0, Color::WHITE));
1336 assert_eq!(scene.command_count(), 0);
1337
1338 assert!(scene.circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE)));
1339 assert_eq!(scene.commands()[0].order(), 0);
1340 }
1341
1342 #[test]
1343 fn background_and_clip_are_validated_when_created() {
1344 assert!(matches!(
1345 Scene::new(Color::rgba(f32::NAN, 0.0, 0.0, 1.0)),
1346 Err(SceneError::InvalidBackground)
1347 ));
1348 assert!(matches!(
1349 Scene::new(Color::rgb(1.01, 0.0, 0.0)),
1350 Err(SceneError::InvalidBackground)
1351 ));
1352 assert_eq!(
1353 ScreenClipRect::new(
1354 LogicalScreenPosition::new(0.0, 0.0),
1355 LogicalScreenPosition::new(0.0, 10.0),
1356 ),
1357 Err(SceneError::InvalidScreenClip)
1358 );
1359 assert_eq!(
1360 ScreenClipRect::new(
1361 LogicalScreenPosition::new(f32::NAN, 0.0),
1362 LogicalScreenPosition::new(10.0, 10.0),
1363 ),
1364 Err(SceneError::InvalidScreenClip)
1365 );
1366 }
1367
1368 #[test]
1369 fn render_bound_scene_colors_must_be_normalized() {
1370 let mut scene = Scene::new(Color::BLACK).unwrap();
1371 assert_eq!(
1372 scene.try_circle(
1373 Vec2::ZERO,
1374 1.0,
1375 ShapeStyle::filled(Color::rgb(2.0, 0.0, 0.0)),
1376 ),
1377 Err(SceneError::InvalidFill(ScenePrimitive::Circle))
1378 );
1379 assert_eq!(
1380 scene.try_line(Vec2::ZERO, Vec2::X, 1.0, Color::rgba(0.0, 0.0, 0.0, -0.01),),
1381 Err(SceneError::InvalidStroke(ScenePrimitive::Line))
1382 );
1383 assert_eq!(scene.command_count(), 0);
1384 }
1385
1386 #[test]
1387 fn depth_does_not_reorder_commands_within_a_layer() {
1388 let mut scene = Scene::new(Color::BLACK).unwrap();
1389 scene
1390 .with_depth(4.0, |scene| {
1391 scene.circle(Vec2::X, 1.0, ShapeStyle::filled(Color::WHITE));
1392 })
1393 .unwrap();
1394 scene.circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE));
1395
1396 assert_eq!(scene.commands()[0].depth(), 4.0);
1397 assert_eq!(scene.commands()[1].depth(), 0.0);
1398 }
1399
1400 #[test]
1401 fn structured_scene_errors_preserve_rejection_reason() {
1402 let mut scene = Scene::new(Color::BLACK).unwrap();
1403
1404 assert_eq!(
1405 scene.try_circle(Vec2::ZERO, -1.0, ShapeStyle::filled(Color::WHITE)),
1406 Err(SceneError::InvalidDimension(ScenePrimitive::Circle))
1407 );
1408 assert_eq!(
1409 scene.try_line(Vec2::ZERO, Vec2::ZERO, 1.0, Color::WHITE),
1410 Err(SceneError::DegenerateGeometry(ScenePrimitive::Line))
1411 );
1412 assert_eq!(
1413 scene.try_circle(
1414 Vec2::ZERO,
1415 1.0,
1416 ShapeStyle {
1417 fill: None,
1418 stroke: None,
1419 shadow: None,
1420 },
1421 ),
1422 Err(SceneError::MissingStyle(ScenePrimitive::Circle))
1423 );
1424 assert_eq!(scene.command_count(), 0);
1425 }
1426
1427 #[test]
1428 fn commands_capture_depth_and_restore_it_after_unwind() {
1429 let mut scene = Scene::new(Color::BLACK).unwrap();
1430 let panic_result = catch_unwind(AssertUnwindSafe(|| {
1431 let _ = scene.with_depth(4.5, |scene| {
1432 scene.circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE));
1433 panic!("intentional depth unwind");
1434 });
1435 }));
1436 assert!(panic_result.is_err());
1437
1438 scene.circle(Vec2::X, 1.0, ShapeStyle::filled(Color::WHITE));
1439
1440 assert_eq!(scene.commands()[0].depth(), 4.5);
1441 assert_eq!(scene.commands()[1].depth(), 0.0);
1442 assert_eq!(
1443 scene.with_depth(f32::NAN, |_| {}),
1444 Err(SceneError::NonFiniteDepth)
1445 );
1446 }
1447
1448 #[test]
1449 fn gradients_sanitize_invalid_and_reversed_configuration() {
1450 let invalid_linear = LinearGradient::new(
1451 Vec2::new(f32::NAN, 0.0),
1452 Vec2::X,
1453 Color::BLACK,
1454 Color::WHITE,
1455 );
1456 assert_eq!(invalid_linear.color_at(Vec2::ZERO), Color::WHITE);
1457
1458 let reversed = RadialGradient::new(Vec2::ZERO, 10.0, 5.0, Color::WHITE, Color::BLACK);
1459 assert_eq!(reversed.inner_radius(), 5.0);
1460 assert_eq!(reversed.outer_radius(), 10.0);
1461 assert_eq!(reversed.color_at(Vec2::ZERO), Color::BLACK);
1462 }
1463
1464 #[test]
1465 fn temporary_screen_clip_restores_state_after_unwind() {
1466 let mut scene = Scene::new(Color::BLACK).unwrap();
1467 let clip = ScreenClipRect::from_min_size(
1468 LogicalScreenPosition::new(0.0, 0.0),
1469 LogicalScreenVector::new(100.0, 100.0),
1470 )
1471 .unwrap();
1472
1473 let panic_result = catch_unwind(AssertUnwindSafe(|| {
1474 let _ = scene.with_screen_clip(clip, |_| panic!("intentional test panic"));
1475 }));
1476 assert!(panic_result.is_err());
1477
1478 assert!(scene.circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE)));
1479 assert_eq!(scene.commands()[0].screen_clip(), None);
1480 }
1481}