1use std::{error::Error, fmt};
2
3use crate::{Color, Vec2};
4
5#[derive(Debug, Clone, Copy, PartialEq)]
13pub struct ParticleInstance2d {
14 world_position: Vec2,
15 radius: f32,
16 color: Color,
17 depth: f32,
18}
19
20impl ParticleInstance2d {
21 pub fn new(
23 world_position: Vec2,
24 radius: f32,
25 color: Color,
26 depth: f32,
27 ) -> Result<Self, ParticleInstanceError> {
28 if !world_position.is_finite() || !radius.is_finite() || !depth.is_finite() {
29 return Err(ParticleInstanceError::NonFinite);
30 }
31 if !color.is_normalized() {
32 return Err(ParticleInstanceError::InvalidColor);
33 }
34 if radius <= 0.0 {
35 return Err(ParticleInstanceError::InvalidRadius);
36 }
37 Ok(Self {
38 world_position,
39 radius,
40 color,
41 depth,
42 })
43 }
44
45 pub fn world_position(self) -> Vec2 {
47 self.world_position
48 }
49
50 pub fn radius(self) -> f32 {
52 self.radius
53 }
54
55 pub fn color(self) -> Color {
57 self.color
58 }
59
60 pub fn depth(self) -> f32 {
62 self.depth
63 }
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum ParticleInstanceError {
69 NonFinite,
71 InvalidRadius,
73 InvalidColor,
75}
76
77impl fmt::Display for ParticleInstanceError {
78 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
79 match self {
80 Self::NonFinite => write!(formatter, "particle instance values must be finite"),
81 Self::InvalidRadius => write!(formatter, "particle radius must be finite and positive"),
82 Self::InvalidColor => {
83 write!(formatter, "particle color must be normalized linear RGBA")
84 }
85 }
86 }
87}
88
89impl Error for ParticleInstanceError {}
90
91#[cfg(test)]
92mod tests {
93 use super::{ParticleInstance2d, ParticleInstanceError};
94 use crate::{Color, Vec2};
95
96 #[test]
97 fn particle_instances_validate_without_the_renderer_feature() {
98 let particle =
99 ParticleInstance2d::new(Vec2::new(3.0, -2.0), 4.5, Color::WHITE, 1.0).unwrap();
100 assert_eq!(particle.world_position(), Vec2::new(3.0, -2.0));
101 assert_eq!(particle.radius(), 4.5);
102 assert_eq!(particle.depth(), 1.0);
103 assert_eq!(particle.color(), Color::WHITE);
104 assert_eq!(
105 ParticleInstance2d::new(Vec2::ZERO, 0.0, Color::WHITE, 0.0),
106 Err(ParticleInstanceError::InvalidRadius)
107 );
108 assert_eq!(
109 ParticleInstance2d::new(Vec2::ZERO, 1.0, Color::WHITE, f32::NAN),
110 Err(ParticleInstanceError::NonFinite)
111 );
112 assert_eq!(
113 ParticleInstance2d::new(Vec2::ZERO, 1.0, Color::rgb(1.01, 0.0, 0.0), 0.0),
114 Err(ParticleInstanceError::InvalidColor)
115 );
116 assert_eq!(
117 ParticleInstance2d::new(Vec2::ZERO, 1.0, Color::rgba(0.0, 0.0, 0.0, -0.01), 0.0,),
118 Err(ParticleInstanceError::InvalidColor)
119 );
120 }
121}