ferravex_play/particles/
beam.rs

1use super::{
2    MAX_EFFECT_LIFETIME, RibbonError, RibbonFacing, RibbonPoint, RibbonTriangle, RibbonTriangles,
3};
4pub const MAX_BEAMS: usize = 4096;
5#[derive(Clone, Copy, Debug, PartialEq)]
6pub struct BeamDesc {
7    pub start: [f32; 3],
8    pub end: [f32; 3],
9    pub start_color: [f32; 4],
10    pub end_color: [f32; 4],
11    pub width: f32,
12    pub lifetime: f32,
13}
14impl Default for BeamDesc {
15    fn default() -> Self {
16        Self {
17            start: [0.; 3],
18            end: [0., 0., 1.],
19            start_color: [1.; 4],
20            end_color: [1.; 4],
21            width: 0.02,
22            lifetime: 0.1,
23        }
24    }
25}
26impl BeamDesc {
27    /// Checks finite endpoints/colors, width in `0..=1e6`, and lifetime in
28    /// `0..=MAX_EFFECT_LIFETIME` excluding zero. Coincident endpoints are valid.
29    /// Colors may contain finite HDR values; they are not clamped.
30    ///
31    /// ```
32    /// use ferravex_play::particles::{BeamDesc, BeamError};
33    /// let mut desc = BeamDesc::default();
34    /// assert_eq!(desc.validate(), Ok(()));
35    /// desc.lifetime = 0.0;
36    /// assert_eq!(desc.validate(), Err(BeamError::InvalidBeam));
37    /// ```
38    pub fn validate(&self) -> Result<(), BeamError> {
39        if !self
40            .start
41            .into_iter()
42            .chain(self.end)
43            .chain(self.start_color)
44            .chain(self.end_color)
45            .chain([self.width, self.lifetime])
46            .all(f32::is_finite)
47            || !(0.0..=1e6).contains(&self.width)
48            || !(0.0..=MAX_EFFECT_LIFETIME).contains(&self.lifetime)
49            || self.lifetime == 0.
50        {
51            Err(BeamError::InvalidBeam)
52        } else {
53            Ok(())
54        }
55    }
56}
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub enum BeamError {
59    InvalidBeam,
60    InvalidCapacity,
61    InvalidDelta,
62    Full,
63}
64#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub enum OverflowPolicy {
66    DropNewest,
67    ReplaceOldest,
68}
69#[derive(Clone, Copy, Debug, PartialEq)]
70pub struct BeamView {
71    pub start: [f32; 3],
72    pub end: [f32; 3],
73    pub start_color: [f32; 4],
74    pub end_color: [f32; 4],
75    pub width: f32,
76    pub normalized_age: f32,
77}
78impl BeamView {
79    pub fn points(self) -> [RibbonPoint; 2] {
80        [
81            RibbonPoint {
82                position: self.start,
83                color: self.start_color,
84                width: self.width,
85                break_before: true,
86            },
87            RibbonPoint {
88                position: self.end,
89                color: self.end_color,
90                width: self.width,
91                break_before: false,
92            },
93        ]
94    }
95
96    /// Generates at most two triangles using the shared ribbon tessellator,
97    /// without allocation or borrowing the view/pool. Invalid geometry fields
98    /// return [`RibbonError::InvalidPoint`]; invalid facing returns
99    /// [`RibbonError::InvalidView`]. `normalized_age` is metadata, not geometry.
100    ///
101    /// Coincident endpoints emit no triangles. Camera-parallel segments use
102    /// projected camera up, then a deterministic perpendicular when up is also
103    /// parallel. Non-finite output vertices are skipped by the tessellator.
104    /// Colors, distance UVs and winding match [`RibbonTriangles`] over
105    /// [`Self::points`]. No random state or elapsed time is consumed.
106    ///
107    /// ```
108    /// use ferravex_play::particles::{BeamDesc, BeamPool, OverflowPolicy, RibbonFacing};
109    /// let mut pool = BeamPool::new(1, OverflowPolicy::DropNewest);
110    /// pool.spawn(BeamDesc::default()).unwrap();
111    /// let beam = pool.iter().next().unwrap();
112    /// let triangles = beam.triangles(RibbonFacing::Camera {
113    ///     eye: [0.0, 0.0, 5.0], up: [0.0, 0.0, 1.0],
114    /// }).unwrap();
115    /// assert_eq!(triangles.count(), 2);
116    /// ```
117    pub fn triangles(
118        self,
119        facing: RibbonFacing,
120    ) -> Result<impl Iterator<Item = RibbonTriangle>, RibbonError> {
121        let points = self.points();
122        if !points.iter().all(RibbonPoint::valid) {
123            return Err(RibbonError::InvalidPoint);
124        }
125        let mut triangles = RibbonTriangles::new(&points, facing, 1.)?;
126        Ok([triangles.next(), triangles.next()].into_iter().flatten())
127    }
128}
129struct Beam {
130    desc: BeamDesc,
131    age: f64,
132    serial: u64,
133}
134pub struct BeamPool {
135    beams: Vec<Beam>,
136    limit: usize,
137    policy: OverflowPolicy,
138    serial: u64,
139    dropped: u64,
140    replaced: u64,
141}
142impl BeamPool {
143    pub fn new(capacity: usize, policy: OverflowPolicy) -> Self {
144        Self::try_new(capacity, policy).expect("beam capacity <= 4096")
145    }
146    pub fn try_new(capacity: usize, policy: OverflowPolicy) -> Result<Self, BeamError> {
147        if capacity > MAX_BEAMS {
148            return Err(BeamError::InvalidCapacity);
149        }
150        Ok(Self {
151            beams: Vec::with_capacity(capacity),
152            limit: capacity,
153            policy,
154            serial: 0,
155            dropped: 0,
156            replaced: 0,
157        })
158    }
159    pub fn len(&self) -> usize {
160        self.beams.len()
161    }
162    pub fn is_empty(&self) -> bool {
163        self.beams.is_empty()
164    }
165    pub fn capacity(&self) -> usize {
166        self.limit
167    }
168    pub fn dropped(&self) -> u64 {
169        self.dropped
170    }
171    pub fn replaced(&self) -> u64 {
172        self.replaced
173    }
174    pub fn clear(&mut self) {
175        self.beams.clear();
176    }
177
178    /// Clears beams, overflow counters and admission ordering while retaining
179    /// the allocated storage, capacity and overflow policy. [`Self::clear`]
180    /// preserves the counters instead.
181    ///
182    /// ```
183    /// use ferravex_play::particles::{BeamDesc, BeamError, BeamPool, OverflowPolicy};
184    /// let mut pool = BeamPool::new(1, OverflowPolicy::DropNewest);
185    /// pool.spawn(BeamDesc::default()).unwrap();
186    /// assert_eq!(pool.spawn(BeamDesc::default()), Err(BeamError::Full));
187    /// pool.reset();
188    /// assert!(pool.is_empty());
189    /// assert_eq!((pool.capacity(), pool.dropped(), pool.replaced()), (1, 0, 0));
190    /// pool.spawn(BeamDesc::default()).unwrap();
191    /// ```
192    pub fn reset(&mut self) {
193        self.clear();
194        self.serial = 0;
195        self.dropped = 0;
196        self.replaced = 0;
197    }
198
199    /// Moves the beam at the current [`Self::iter`] index without changing its
200    /// age, lifetime, colors, width or replacement priority. Both endpoints must
201    /// be finite; coincident endpoints are allowed. Invalid input leaves the
202    /// entire pool unchanged. Valid input with no beam at `index` returns `false`.
203    ///
204    /// Indices are temporary positions, not identities: aging can compact the
205    /// pool and spawning can replace a beam. Reacquire indices after those calls.
206    ///
207    /// ```
208    /// use ferravex_play::particles::{BeamDesc, BeamPool, OverflowPolicy};
209    /// let mut pool = BeamPool::new(1, OverflowPolicy::DropNewest);
210    /// pool.spawn(BeamDesc { lifetime: 1.0, ..BeamDesc::default() }).unwrap();
211    /// pool.update(0.25).unwrap();
212    /// assert!(pool.set_endpoints(0, [1.0, 0.0, 0.0], [3.0, 0.0, 0.0]).unwrap());
213    /// assert_eq!(pool.iter().next().unwrap().normalized_age, 0.25);
214    /// assert!(!pool.set_endpoints(1, [0.0; 3], [0.0; 3]).unwrap());
215    /// ```
216    pub fn set_endpoints(
217        &mut self,
218        index: usize,
219        start: [f32; 3],
220        end: [f32; 3],
221    ) -> Result<bool, BeamError> {
222        if !start.into_iter().chain(end).all(f32::is_finite) {
223            return Err(BeamError::InvalidBeam);
224        }
225        let Some(beam) = self.beams.get_mut(index) else {
226            return Ok(false);
227        };
228        beam.desc.start = start;
229        beam.desc.end = end;
230        Ok(true)
231    }
232
233    /// Reconfigures a beam at the current [`Self::iter`] index and restarts its
234    /// lifetime/fade at age zero. It becomes newest for equal-age replacement
235    /// ties. This does not spawn, change length or increment overflow counters.
236    ///
237    /// Validation precedes lookup: invalid descriptors return
238    /// [`BeamError::InvalidBeam`] without mutation, and valid descriptors with
239    /// no beam at `index` return `false`. Indices have the same temporary meaning
240    /// as in [`Self::set_endpoints`].
241    ///
242    /// ```
243    /// use ferravex_play::particles::{BeamDesc, BeamPool, OverflowPolicy};
244    /// let mut pool = BeamPool::new(1, OverflowPolicy::ReplaceOldest);
245    /// pool.spawn(BeamDesc { lifetime: 1.0, ..BeamDesc::default() }).unwrap();
246    /// pool.update(0.5).unwrap();
247    /// assert!(pool.reset_beam(0, BeamDesc::default()).unwrap());
248    /// assert_eq!(pool.iter().next().unwrap().normalized_age, 0.0);
249    /// assert_eq!(pool.replaced(), 0);
250    /// ```
251    pub fn reset_beam(&mut self, index: usize, desc: BeamDesc) -> Result<bool, BeamError> {
252        desc.validate()?;
253        let Some(beam) = self.beams.get_mut(index) else {
254            return Ok(false);
255        };
256        *beam = Beam {
257            desc,
258            age: 0.,
259            serial: self.serial,
260        };
261        self.serial = self.serial.saturating_add(1);
262        Ok(true)
263    }
264
265    pub fn spawn(&mut self, desc: BeamDesc) -> Result<(), BeamError> {
266        desc.validate()?;
267        if self.limit == 0
268            || self.beams.len() == self.limit && self.policy == OverflowPolicy::DropNewest
269        {
270            self.dropped = self.dropped.saturating_add(1);
271            return Err(BeamError::Full);
272        }
273        let beam = Beam {
274            desc,
275            age: 0.,
276            serial: self.serial,
277        };
278        self.serial = self.serial.saturating_add(1);
279        if self.beams.len() == self.limit {
280            let oldest = self
281                .beams
282                .iter()
283                .enumerate()
284                .max_by(|(_, a), (_, b)| {
285                    a.age
286                        .total_cmp(&b.age)
287                        .then_with(|| b.serial.cmp(&a.serial))
288                })
289                .map(|(i, _)| i)
290                .expect("nonempty full beam pool");
291            self.beams[oldest] = beam;
292            self.replaced = self.replaced.saturating_add(1);
293        } else {
294            self.beams.push(beam);
295        }
296        Ok(())
297    }
298    pub fn update(&mut self, dt: f32) -> Result<(), BeamError> {
299        if !dt.is_finite() || dt < 0. {
300            return Err(BeamError::InvalidDelta);
301        }
302        self.beams.retain_mut(|b| {
303            b.age += f64::from(dt);
304            b.age < f64::from(b.desc.lifetime)
305        });
306        Ok(())
307    }
308    pub fn iter(&self) -> impl ExactSizeIterator<Item = BeamView> + '_ {
309        self.beams.iter().map(|b| {
310            let t = (b.age / f64::from(b.desc.lifetime)) as f32;
311            let fade = |mut color: [f32; 4]| {
312                color[3] *= 1. - t;
313                color
314            };
315            BeamView {
316                start: b.desc.start,
317                end: b.desc.end,
318                start_color: fade(b.desc.start_color),
319                end_color: fade(b.desc.end_color),
320                width: b.desc.width,
321                normalized_age: t,
322            }
323        })
324    }
325}
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330
331    fn desc(x: f32) -> BeamDesc {
332        BeamDesc {
333            start: [x, 0., 0.],
334            end: [x, 0., 2.],
335            start_color: [2., 0., 0., 0.8],
336            end_color: [0., 3., 0., 0.4],
337            width: 0.5,
338            lifetime: 2.,
339        }
340    }
341
342    fn view(desc: BeamDesc) -> BeamView {
343        BeamView {
344            start: desc.start,
345            end: desc.end,
346            start_color: desc.start_color,
347            end_color: desc.end_color,
348            width: desc.width,
349            normalized_age: 0.,
350        }
351    }
352
353    fn state(pool: &BeamPool) -> (Vec<(BeamDesc, f64, u64)>, u64, u64, u64) {
354        (
355            pool.beams
356                .iter()
357                .map(|b| (b.desc, b.age, b.serial))
358                .collect(),
359            pool.serial,
360            pool.dropped(),
361            pool.replaced(),
362        )
363    }
364
365    #[test]
366    fn descriptor_validation_preserves_spawn_bounds_and_rejection_is_transactional() {
367        let valid = BeamDesc {
368            start: [f32::MAX; 3],
369            end: [f32::MAX; 3],
370            start_color: [-f32::MAX; 4],
371            end_color: [f32::MAX; 4],
372            width: 1e6,
373            lifetime: MAX_EFFECT_LIFETIME,
374        };
375        assert_eq!(valid.validate(), Ok(()));
376        assert_eq!(BeamDesc { width: 0., ..valid }.validate(), Ok(()));
377        let mut pool = BeamPool::new(1, OverflowPolicy::ReplaceOldest);
378        pool.spawn(desc(0.)).unwrap();
379        pool.update(0.5).unwrap();
380        let before = state(&pool);
381        let mut invalid = vec![
382            BeamDesc {
383                width: -1.,
384                ..valid
385            },
386            BeamDesc {
387                width: 1e6 + 1.,
388                ..valid
389            },
390            BeamDesc {
391                lifetime: 0.,
392                ..valid
393            },
394            BeamDesc {
395                lifetime: -1.,
396                ..valid
397            },
398            BeamDesc {
399                lifetime: MAX_EFFECT_LIFETIME + 1.,
400                ..valid
401            },
402        ];
403        for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
404            invalid.extend([
405                BeamDesc {
406                    start: [value; 3],
407                    ..valid
408                },
409                BeamDesc {
410                    end: [value; 3],
411                    ..valid
412                },
413                BeamDesc {
414                    start_color: [value; 4],
415                    ..valid
416                },
417                BeamDesc {
418                    end_color: [value; 4],
419                    ..valid
420                },
421                BeamDesc {
422                    width: value,
423                    ..valid
424                },
425                BeamDesc {
426                    lifetime: value,
427                    ..valid
428                },
429            ]);
430        }
431        for bad in invalid {
432            assert_eq!(bad.validate(), Err(BeamError::InvalidBeam));
433            assert_eq!(pool.spawn(bad), Err(BeamError::InvalidBeam));
434            assert_eq!(pool.reset_beam(0, bad), Err(BeamError::InvalidBeam));
435            assert_eq!(
436                pool.reset_beam(usize::MAX, bad),
437                Err(BeamError::InvalidBeam)
438            );
439            assert_eq!(state(&pool), before);
440        }
441    }
442
443    #[test]
444    fn moving_endpoints_preserves_fade_lifetime_and_replacement_priority() {
445        let mut pool = BeamPool::new(2, OverflowPolicy::ReplaceOldest);
446        pool.spawn(desc(0.)).unwrap();
447        pool.spawn(desc(1.)).unwrap();
448        pool.update(0.5).unwrap();
449        let before = pool.iter().next().unwrap();
450        assert!(pool.set_endpoints(0, [3.; 3], [4.; 3]).unwrap());
451        let after = pool.iter().next().unwrap();
452        assert_eq!(
453            after,
454            BeamView {
455                start: [3.; 3],
456                end: [4.; 3],
457                ..before
458            }
459        );
460        pool.spawn(desc(2.)).unwrap();
461        assert_eq!(
462            pool.iter().map(|b| b.start[0]).collect::<Vec<_>>(),
463            [2., 1.]
464        );
465        assert_eq!(pool.replaced(), 1);
466        assert!(pool.set_endpoints(1, [9.; 3], [9.; 3]).unwrap());
467        pool.update(1.5).unwrap();
468        assert_eq!(pool.len(), 1);
469        assert_eq!(pool.iter().next().unwrap().start, desc(2.).start);
470    }
471
472    #[test]
473    fn invalid_endpoints_deltas_and_missing_indices_leave_all_state_unchanged() {
474        let mut pool = BeamPool::new(1, OverflowPolicy::DropNewest);
475        pool.spawn(desc(0.)).unwrap();
476        assert_eq!(pool.spawn(desc(1.)), Err(BeamError::Full));
477        pool.update(0.5).unwrap();
478        let before = state(&pool);
479        for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
480            for (start, end) in [([bad; 3], [1.; 3]), ([1.; 3], [bad; 3])] {
481                assert_eq!(
482                    pool.set_endpoints(0, start, end),
483                    Err(BeamError::InvalidBeam)
484                );
485                assert_eq!(
486                    pool.set_endpoints(usize::MAX, start, end),
487                    Err(BeamError::InvalidBeam)
488                );
489            }
490            assert_eq!(pool.update(bad), Err(BeamError::InvalidDelta));
491            assert_eq!(state(&pool), before);
492        }
493        assert_eq!(pool.update(-0.5), Err(BeamError::InvalidDelta));
494        assert_eq!(pool.set_endpoints(1, [0.; 3], [0.; 3]), Ok(false));
495        assert_eq!(pool.reset_beam(usize::MAX, desc(1.)), Ok(false));
496        pool.update(0.).unwrap();
497        assert_eq!(state(&pool), before);
498        pool.update(1.5).unwrap();
499        assert_eq!(pool.set_endpoints(0, [0.; 3], [0.; 3]), Ok(false));
500        assert_eq!(pool.reset_beam(0, desc(2.)), Ok(false));
501        assert!(pool.is_empty());
502    }
503
504    #[test]
505    fn reset_beam_restarts_style_and_lifetime_without_counting_an_overflow() {
506        let mut pool = BeamPool::new(1, OverflowPolicy::DropNewest);
507        pool.spawn(desc(0.)).unwrap();
508        pool.update(1.).unwrap();
509        let restarted = BeamDesc {
510            lifetime: 0.5,
511            width: 2.,
512            ..desc(9.)
513        };
514        assert_eq!(pool.reset_beam(0, restarted), Ok(true));
515        assert_eq!(pool.iter().next().unwrap(), view(restarted));
516        assert_eq!((pool.len(), pool.dropped(), pool.replaced()), (1, 0, 0));
517        pool.update(0.25).unwrap();
518        let faded = pool.iter().next().unwrap();
519        assert_eq!(faded.normalized_age, 0.5);
520        assert_eq!(faded.start_color[3], restarted.start_color[3] * 0.5);
521        assert_eq!(faded.end_color[3], restarted.end_color[3] * 0.5);
522        pool.update(0.25).unwrap();
523        assert!(pool.is_empty());
524    }
525
526    #[test]
527    fn restarted_beam_is_newest_for_equal_age_replacement() {
528        let mut pool = BeamPool::new(2, OverflowPolicy::ReplaceOldest);
529        pool.spawn(desc(0.)).unwrap();
530        pool.spawn(desc(1.)).unwrap();
531        pool.reset_beam(0, desc(2.)).unwrap();
532        pool.spawn(desc(3.)).unwrap();
533        assert_eq!(
534            pool.iter().map(|b| b.start[0]).collect::<Vec<_>>(),
535            [2., 3.]
536        );
537        assert_eq!(pool.replaced(), 1);
538    }
539
540    #[test]
541    fn reset_matches_fresh_pool_and_retains_storage_and_overflow_policy() {
542        for policy in [OverflowPolicy::DropNewest, OverflowPolicy::ReplaceOldest] {
543            let mut pool = BeamPool::new(2, policy);
544            let storage = pool.beams.as_ptr();
545            let allocated = pool.beams.capacity();
546            for _ in 0..32 {
547                pool.spawn(desc(0.)).unwrap();
548                pool.spawn(desc(1.)).unwrap();
549                let result = pool.spawn(desc(2.));
550                if policy == OverflowPolicy::DropNewest {
551                    assert_eq!(result, Err(BeamError::Full));
552                    assert_eq!(pool.dropped(), 1);
553                } else {
554                    result.unwrap();
555                    assert_eq!(pool.replaced(), 1);
556                }
557                let counters = (pool.dropped(), pool.replaced());
558                pool.clear();
559                assert_eq!((pool.dropped(), pool.replaced()), counters);
560                pool.reset();
561                let fresh = BeamPool::new(2, policy);
562                assert_eq!(state(&pool), state(&fresh));
563                assert_eq!(pool.capacity(), fresh.capacity());
564                assert_eq!(pool.beams.as_ptr(), storage);
565                assert_eq!(pool.beams.capacity(), allocated);
566            }
567        }
568        let mut empty = BeamPool::new(0, OverflowPolicy::ReplaceOldest);
569        assert_eq!(empty.spawn(desc(0.)), Err(BeamError::Full));
570        empty.reset();
571        assert_eq!(empty.dropped(), 0);
572        assert_eq!(empty.reset_beam(0, desc(0.)), Ok(false));
573        assert_eq!(empty.spawn(desc(0.)), Err(BeamError::Full));
574    }
575
576    #[test]
577    fn geometry_matches_existing_ribbon_colors_uvs_winding_and_bounds() {
578        let beam = view(desc(0.));
579        for facing in [
580            RibbonFacing::Plane {
581                normal: [0., 1., 0.],
582            },
583            RibbonFacing::Camera {
584                eye: [1., 2., 3.],
585                up: [0., 1., 0.],
586            },
587        ] {
588            let points = beam.points();
589            let expected: Vec<_> = RibbonTriangles::new(&points, facing, 1.).unwrap().collect();
590            let actual: Vec<_> = beam.triangles(facing).unwrap().collect();
591            assert_eq!(actual, expected);
592            assert_eq!(actual.len(), 2);
593            for v in actual.iter().flat_map(|t| t.vertices) {
594                let (center, color, distance) = if v.uv[0] == 0. {
595                    (beam.start, beam.start_color, 0.)
596                } else {
597                    (beam.end, beam.end_color, 2.)
598                };
599                assert_eq!(v.color, color);
600                assert_eq!(v.uv[0], distance);
601                let offset = ferravex_math::Vec3::from_array(v.position)
602                    - ferravex_math::Vec3::from_array(center);
603                assert!((offset.length() - beam.width * 0.5).abs() < 1e-6);
604            }
605        }
606    }
607
608    #[test]
609    fn coincident_endpoints_can_move_apart_and_geometry_never_mutates_age() {
610        let mut pool = BeamPool::new(1, OverflowPolicy::DropNewest);
611        pool.spawn(desc(0.)).unwrap();
612        pool.update(0.5).unwrap();
613        let facing = RibbonFacing::Camera {
614            eye: [0.; 3],
615            up: [0., 0., 1.],
616        };
617        pool.set_endpoints(0, [0.; 3], [0.; 3]).unwrap();
618        let before = state(&pool);
619        assert_eq!(
620            pool.iter()
621                .next()
622                .unwrap()
623                .triangles(facing)
624                .unwrap()
625                .count(),
626            0
627        );
628        assert_eq!(state(&pool), before);
629        pool.set_endpoints(0, desc(0.).start, desc(0.).end).unwrap();
630        let beam = pool.iter().next().unwrap();
631        assert_eq!(beam.triangles(facing).unwrap().count(), 2);
632        assert_eq!(beam.normalized_age, 0.25);
633    }
634
635    #[test]
636    fn camera_parallel_and_coincident_eye_geometry_is_finite_and_repeatable() {
637        for direction in [
638            [1., 0., 0.],
639            [0., 1., 0.],
640            [0., 0., 1.],
641            [1., 1., 1.],
642            [1., 2., -3.],
643        ] {
644            let beam = view(BeamDesc {
645                start: [0.; 3],
646                end: direction,
647                ..desc(0.)
648            });
649            for distance in [-2., 0., 0.5, 1., 2.] {
650                for up in [direction, direction.map(|n| -n), [0., 1., 0.]] {
651                    let facing = RibbonFacing::Camera {
652                        eye: direction.map(|n| n * distance),
653                        up,
654                    };
655                    let first: Vec<_> = beam.triangles(facing).unwrap().collect();
656                    let second: Vec<_> = beam.triangles(facing).unwrap().collect();
657                    assert_eq!(first, second);
658                    assert_eq!(first.len(), 2);
659                    for triangle in first {
660                        for v in triangle.vertices {
661                            assert!(
662                                v.position
663                                    .into_iter()
664                                    .chain(v.color)
665                                    .chain(v.uv)
666                                    .all(f32::is_finite)
667                            );
668                            let center = if v.uv[0] == 0. { beam.start } else { beam.end };
669                            let offset = ferravex_math::Vec3::from_array(v.position)
670                                - ferravex_math::Vec3::from_array(center);
671                            assert!((offset.length() - beam.width * 0.5).abs() < 1e-6);
672                            assert!(
673                                offset.dot(ferravex_math::Vec3::from_array(direction)).abs() < 1e-6
674                            );
675                        }
676                        let positions = triangle
677                            .vertices
678                            .map(|v| ferravex_math::Vec3::from_array(v.position));
679                        assert!(
680                            (positions[1] - positions[0])
681                                .cross(positions[2] - positions[0])
682                                .length()
683                                > 0.
684                        );
685                    }
686                }
687            }
688        }
689    }
690
691    #[test]
692    fn geometry_rejects_invalid_fields_and_extreme_segments_stay_finite_and_bounded() {
693        let beam = view(desc(0.));
694        let facing = RibbonFacing::Plane {
695            normal: [0., 1., 0.],
696        };
697        for invalid in [
698            BeamView {
699                start: [f32::NAN; 3],
700                ..beam
701            },
702            BeamView {
703                end: [f32::INFINITY; 3],
704                ..beam
705            },
706            BeamView {
707                start_color: [f32::NAN; 4],
708                ..beam
709            },
710            BeamView {
711                end_color: [f32::INFINITY; 4],
712                ..beam
713            },
714            BeamView { width: -1., ..beam },
715            BeamView {
716                width: f32::NAN,
717                ..beam
718            },
719            BeamView {
720                width: 1e6 + 1.,
721                ..beam
722            },
723        ] {
724            assert_eq!(
725                invalid.triangles(facing).err(),
726                Some(RibbonError::InvalidPoint)
727            );
728        }
729        for invalid in [
730            RibbonFacing::Plane { normal: [0.; 3] },
731            RibbonFacing::Camera {
732                eye: [f32::NAN; 3],
733                up: [0., 1., 0.],
734            },
735            RibbonFacing::Camera {
736                eye: [0.; 3],
737                up: [0.; 3],
738            },
739            RibbonFacing::Camera {
740                eye: [0.; 3],
741                up: [f32::INFINITY; 3],
742            },
743        ] {
744            assert_eq!(
745                beam.triangles(invalid).err(),
746                Some(RibbonError::InvalidView)
747            );
748        }
749        let huge = BeamView {
750            start: [-f32::MAX; 3],
751            end: [f32::MAX; 3],
752            ..beam
753        };
754        let triangles: Vec<_> = huge.triangles(facing).unwrap().collect();
755        assert!(triangles.len() <= 2);
756        for vertex in triangles.iter().flat_map(|t| t.vertices) {
757            assert!(
758                vertex
759                    .position
760                    .into_iter()
761                    .chain(vertex.uv)
762                    .all(f32::is_finite)
763            );
764        }
765    }
766}