ferravex_play/particles/
ribbon.rs

1use ferravex_math::Vec3;
2pub const MAX_RIBBON_POINTS: usize = 4096;
3/// Largest accepted full ribbon width, in world units.
4pub const MAX_RIBBON_WIDTH: f32 = 1e6;
5#[derive(Clone, Copy, Debug, Default, PartialEq)]
6pub struct RibbonPoint {
7    pub position: [f32; 3],
8    pub color: [f32; 4],
9    pub width: f32,
10    pub break_before: bool,
11}
12impl RibbonPoint {
13    pub fn valid(&self) -> bool {
14        self.position
15            .into_iter()
16            .chain(self.color)
17            .all(f32::is_finite)
18            && valid_width(self.width)
19    }
20}
21pub trait RibbonSource {
22    fn point_count(&self) -> usize;
23    fn point(&self, index: usize) -> Option<RibbonPoint>;
24}
25impl RibbonSource for [RibbonPoint] {
26    fn point_count(&self) -> usize {
27        self.len()
28    }
29    fn point(&self, index: usize) -> Option<RibbonPoint> {
30        self.get(index).copied()
31    }
32}
33impl<const N: usize> RibbonSource for [RibbonPoint; N] {
34    fn point_count(&self) -> usize {
35        N
36    }
37    fn point(&self, index: usize) -> Option<RibbonPoint> {
38        self.get(index).copied()
39    }
40}
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub enum RibbonError {
43    /// A point has non-finite components or a width outside `0..=MAX_RIBBON_WIDTH`.
44    InvalidPoint,
45    InvalidCapacity,
46    InvalidView,
47    Full,
48}
49pub struct RibbonPath {
50    points: Vec<RibbonPoint>,
51    capacity: usize,
52}
53impl RibbonPath {
54    pub fn new(capacity: usize) -> Result<Self, RibbonError> {
55        if capacity > MAX_RIBBON_POINTS {
56            return Err(RibbonError::InvalidCapacity);
57        }
58        Ok(Self {
59            points: Vec::with_capacity(capacity),
60            capacity,
61        })
62    }
63    pub fn set(&mut self, points: &[RibbonPoint]) -> Result<(), RibbonError> {
64        if points.len() > self.capacity {
65            return Err(RibbonError::Full);
66        }
67        if !points.iter().all(RibbonPoint::valid) {
68            return Err(RibbonError::InvalidPoint);
69        }
70        self.points.clear();
71        self.points.extend_from_slice(points);
72        Ok(())
73    }
74    /// Sets every point's full width without allocating. An invalid width returns
75    /// [`RibbonError::InvalidPoint`] and leaves the path unchanged, even if empty.
76    /// Zero is valid and collapses the ribbon to its centerline.
77    ///
78    /// ```
79    /// use ferravex_play::particles::{RibbonError, RibbonPath, RibbonPoint};
80    /// let mut path = RibbonPath::new(2)?;
81    /// path.set(&[RibbonPoint::default(); 2])?;
82    /// path.set_width(0.5)?;
83    /// assert!(path.points().iter().all(|p| p.width == 0.5));
84    /// assert_eq!(path.set_width(-1.0), Err(RibbonError::InvalidPoint));
85    /// # Ok::<(), RibbonError>(())
86    /// ```
87    pub fn set_width(&mut self, width: f32) -> Result<(), RibbonError> {
88        if !valid_width(width) {
89            return Err(RibbonError::InvalidPoint);
90        }
91        for point in &mut self.points {
92            point.width = width;
93        }
94        Ok(())
95    }
96    /// Replaces widths with a linear taper by world-space arc length, from the
97    /// first to the last point of **each** run separated by `break_before`.
98    /// These are absolute full widths, not multipliers of the existing widths.
99    ///
100    /// Coincident points have equal widths; singleton and entirely coincident
101    /// runs use `start_width`. Empty paths are allowed. Both widths must be finite
102    /// and in `0..=MAX_RIBBON_WIDTH`, otherwise [`RibbonError::InvalidPoint`] is
103    /// returned without changing the path. Uses two passes per run and no allocation.
104    ///
105    /// ```
106    /// use ferravex_play::particles::{RibbonError, RibbonPath, RibbonPoint};
107    /// let mut path = RibbonPath::new(3)?;
108    /// path.set(&[0.0, 1.0, 4.0].map(|x| RibbonPoint {
109    ///     position: [x, 0.0, 0.0], ..RibbonPoint::default()
110    /// }))?;
111    /// path.set_taper(2.0, 0.0)?;
112    /// assert_eq!(path.points().iter().map(|p| p.width).collect::<Vec<_>>(),
113    ///            [2.0, 1.5, 0.0]);
114    /// # Ok::<(), RibbonError>(())
115    /// ```
116    pub fn set_taper(&mut self, start_width: f32, end_width: f32) -> Result<(), RibbonError> {
117        if !valid_width(start_width) || !valid_width(end_width) {
118            return Err(RibbonError::InvalidPoint);
119        }
120        let mut start = 0;
121        while start < self.points.len() {
122            let mut end = start + 1;
123            let mut length = 0.;
124            while end < self.points.len() && !self.points[end].break_before {
125                length += point_distance(self.points[end - 1].position, self.points[end].position);
126                end += 1;
127            }
128            let mut distance = 0.;
129            for i in start..end {
130                if i > start {
131                    distance +=
132                        point_distance(self.points[i - 1].position, self.points[i].position);
133                }
134                let t = if length > 0. { distance / length } else { 0. };
135                self.points[i].width =
136                    (f64::from(start_width) * (1. - t) + f64::from(end_width) * t) as f32;
137            }
138            start = end;
139        }
140        Ok(())
141    }
142    pub fn clear(&mut self) {
143        self.points.clear();
144    }
145    pub fn points(&self) -> &[RibbonPoint] {
146        &self.points
147    }
148}
149impl RibbonSource for RibbonPath {
150    fn point_count(&self) -> usize {
151        self.points.len()
152    }
153    fn point(&self, index: usize) -> Option<RibbonPoint> {
154        self.points.get(index).copied()
155    }
156}
157#[derive(Clone, Copy, Debug, PartialEq)]
158pub enum RibbonFacing {
159    /// XY for 2D: normal `[0,0,1]`. XZ ground marks: normal `[0,1,0]`.
160    Plane {
161        normal: [f32; 3],
162    },
163    Camera {
164        eye: [f32; 3],
165        up: [f32; 3],
166    },
167}
168#[derive(Clone, Copy, Debug, PartialEq)]
169pub struct RibbonVertex {
170    pub position: [f32; 3],
171    pub color: [f32; 4],
172    pub uv: [f32; 2],
173}
174#[derive(Clone, Copy, Debug, PartialEq)]
175pub struct RibbonTriangle {
176    pub vertices: [RibbonVertex; 3],
177}
178/// Triangle iterator with bounded miters and explicit breaks; no allocation.
179///
180/// Coincident segments emit no triangles and do not advance UV distance. Joins
181/// look through coincident points within a run, retaining each endpoint's authored
182/// width/color. Near reversals (tangent dot product <= -0.9999) use independent
183/// butt ends instead of an unstable miter, as do nearly opposing facing sides.
184/// Nearly view-aligned segments use a finite perpendicular fallback. Zero-width
185/// segments may emit collapsed triangles.
186///
187/// UV `u` is world-space distance, saturated at `f32::MAX`. Breaks and missing or
188/// invalid source points reset it and stop neighbor lookup. Wide intermediates
189/// keep finite extreme positions from poisoning subsequent geometry.
190pub struct RibbonTriangles<'a, S: RibbonSource + ?Sized> {
191    source: &'a S,
192    facing: RibbonFacing,
193    miter: f32,
194    index: usize,
195    pending: Option<RibbonTriangle>,
196    distance: f64,
197    count: usize,
198}
199impl<'a, S: RibbonSource + ?Sized> RibbonTriangles<'a, S> {
200    pub fn new(source: &'a S, facing: RibbonFacing, miter_limit: f32) -> Result<Self, RibbonError> {
201        let valid = match facing {
202            RibbonFacing::Plane { normal } => Vec3::from_array(normal).try_normalize().is_some(),
203            RibbonFacing::Camera { eye, up } => {
204                eye.into_iter().all(f32::is_finite)
205                    && Vec3::from_array(up).try_normalize().is_some()
206            }
207        };
208        if !valid || !miter_limit.is_finite() || !(1.0..=4.).contains(&miter_limit) {
209            return Err(RibbonError::InvalidView);
210        }
211        let count = source.point_count();
212        if count > MAX_RIBBON_POINTS {
213            return Err(RibbonError::InvalidCapacity);
214        }
215        Ok(Self {
216            source,
217            count,
218            facing,
219            miter: miter_limit,
220            index: 0,
221            pending: None,
222            distance: 0.,
223        })
224    }
225    fn side(&self, point: Vec3, tangent: Vec3) -> Vec3 {
226        let n = match self.facing {
227            RibbonFacing::Plane { normal } => Vec3::from_array(normal).normalize_or_zero(),
228            RibbonFacing::Camera { eye, .. } => {
229                point_direction(point.to_array(), eye).unwrap_or(Vec3::ZERO)
230            }
231        };
232        if let Some(side) = stable_normal(n.cross(tangent)) {
233            return side;
234        }
235        let fallback = match self.facing {
236            RibbonFacing::Plane { .. } => tangent.any_orthonormal_vector(),
237            RibbonFacing::Camera { up, .. } => Vec3::from_array(up).normalize_or_zero(),
238        };
239        stable_normal(fallback - tangent * fallback.dot(tangent))
240            .unwrap_or_else(|| tangent.any_orthonormal_vector())
241    }
242    fn neighbor_tangent(
243        &self,
244        mut index: usize,
245        forward: bool,
246        point: RibbonPoint,
247    ) -> Option<Vec3> {
248        let mut current = point;
249        loop {
250            index = if forward {
251                (index + 1 < self.count).then_some(index + 1)?
252            } else {
253                if current.break_before {
254                    return None;
255                }
256                index.checked_sub(1)?
257            };
258            let neighbor = self.source.point(index)?;
259            if !neighbor.valid() || (forward && neighbor.break_before) {
260                return None;
261            }
262            let direction = if forward {
263                point_direction(point.position, neighbor.position)
264            } else {
265                point_direction(neighbor.position, point.position)
266            };
267            if direction.is_some() {
268                return direction;
269            }
270            current = neighbor;
271        }
272    }
273    fn offset(&self, index: usize, tangent: Vec3, forward: bool, point: RibbonPoint) -> Vec3 {
274        let p = Vec3::from_array(point.position);
275        let side = self.side(p, tangent);
276        let Some(other) = self.neighbor_tangent(index, forward, point) else {
277            return side * (point.width * 0.5);
278        };
279        if tangent.dot(other) <= -0.9999 {
280            return side * (point.width * 0.5);
281        }
282        let other_side = self.side(p, other);
283        let Some(miter) = stable_normal(side + other_side) else {
284            return side * (point.width * 0.5);
285        };
286        // Symmetric evaluation gives adjoining segments the same join even when
287        // f32 rounding makes their individual dot products differ slightly.
288        let denominator = miter.dot(side).abs().min(miter.dot(other_side).abs());
289        miter * (point.width * 0.5 * (1. / denominator.max(0.0001)).min(self.miter))
290    }
291}
292impl<S: RibbonSource + ?Sized> Iterator for RibbonTriangles<'_, S> {
293    type Item = RibbonTriangle;
294    fn next(&mut self) -> Option<Self::Item> {
295        if let Some(triangle) = self.pending.take() {
296            return Some(triangle);
297        }
298        while self.index + 1 < self.count {
299            let i = self.index;
300            self.index += 1;
301            let (Some(a), Some(b)) = (self.source.point(i), self.source.point(i + 1)) else {
302                self.distance = 0.;
303                continue;
304            };
305            if b.break_before || !a.valid() || !b.valid() {
306                self.distance = 0.;
307                continue;
308            }
309            let (pa, pb) = (Vec3::from_array(a.position), Vec3::from_array(b.position));
310            let Some(tangent) = point_direction(a.position, b.position) else {
311                continue;
312            };
313            let oa = self.offset(i, tangent, false, a);
314            let ob = self.offset(i + 1, tangent, true, b);
315            let end = self.distance + point_distance(a.position, b.position);
316            let start_u = self.distance.min(f64::from(f32::MAX)) as f32;
317            let end_u = end.min(f64::from(f32::MAX)) as f32;
318            let vertex = |p: Vec3, color, uv| RibbonVertex {
319                position: p.to_array(),
320                color,
321                uv,
322            };
323            let v = [
324                vertex(pa - oa, a.color, [start_u, 0.]),
325                vertex(pa + oa, a.color, [start_u, 1.]),
326                vertex(pb - ob, b.color, [end_u, 0.]),
327                vertex(pb + ob, b.color, [end_u, 1.]),
328            ];
329            self.distance = end;
330            if !v
331                .iter()
332                .all(|p| p.position.into_iter().chain(p.uv).all(f32::is_finite))
333            {
334                continue;
335            }
336            self.pending = Some(RibbonTriangle {
337                vertices: [v[2], v[1], v[3]],
338            });
339            return Some(RibbonTriangle {
340                vertices: [v[0], v[1], v[2]],
341            });
342        }
343        None
344    }
345}
346
347fn valid_width(width: f32) -> bool {
348    width.is_finite() && (0.0..=MAX_RIBBON_WIDTH).contains(&width)
349}
350
351// Inputs here are sums, crosses or projections of unit directions. Do not turn
352// cancellation noise at alignment/reversal into a full-width arbitrary normal.
353fn stable_normal(direction: Vec3) -> Option<Vec3> {
354    if direction.length_squared() > 1e-8 {
355        direction.try_normalize()
356    } else {
357        None
358    }
359}
360
361fn point_delta(a: [f32; 3], b: [f32; 3]) -> [f64; 3] {
362    std::array::from_fn(|i| f64::from(b[i]) - f64::from(a[i]))
363}
364
365fn point_distance(a: [f32; 3], b: [f32; 3]) -> f64 {
366    point_delta(a, b)
367        .into_iter()
368        .map(|d| d * d)
369        .sum::<f64>()
370        .sqrt()
371}
372
373fn point_direction(a: [f32; 3], b: [f32; 3]) -> Option<Vec3> {
374    let delta = point_delta(a, b);
375    let length = delta.into_iter().map(|d| d * d).sum::<f64>().sqrt();
376    (length > 0.).then(|| Vec3::from_array(delta.map(|d| (d / length) as f32)))
377}