embedded-3dgfx 0.6.2

3D graphics rendering for embedded systems (fork of embedded-gfx by Kezii)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! Fixed-capacity, no-alloc particle system for embedded environments.
//!
//! Each particle is rendered as a camera-facing billboard quad whose colour
//! and size interpolate linearly between their birth and death values.
//!
//! # Example
//! ```
//! use embedded_3dgfx::particles::{ParticleSpawn, ParticleSystem};
//! use nalgebra::{Point3, Vector3};
//! use embedded_graphics_core::pixelcolor::Rgb565;
//!
//! let mut sys: ParticleSystem<64> = ParticleSystem::new();
//! sys.spawn(ParticleSpawn {
//!     position:     Point3::new(0.0, 0.0, 0.0),
//!     velocity:     Vector3::new(0.0, 2.0, 0.0),
//!     acceleration: Vector3::zeros(),
//!     color_start:  Rgb565::new(31, 40, 0),
//!     color_end:    Rgb565::new(10, 0, 0),
//!     size_start:   0.2,
//!     size_end:     0.0,
//!     lifetime:     1.5,
//! });
//! sys.update(0.016, Vector3::new(0.0, -9.81, 0.0));
//! ```

use embedded_graphics_core::pixelcolor::{Rgb565, RgbColor};
use nalgebra::{Point3, Vector3};

use crate::billboard::Billboard;

/// State for a single live particle.
#[derive(Clone, Copy)]
pub struct Particle {
    /// Current world-space position.
    pub position: Point3<f32>,
    /// Current velocity (world units/second).
    pub velocity: Vector3<f32>,
    /// Constant per-particle acceleration (applied in addition to gravity).
    pub acceleration: Vector3<f32>,
    /// Colour at birth (t = 0).
    pub color_start: Rgb565,
    /// Colour at death (t = 1).
    pub color_end: Rgb565,
    /// Billboard half-size at birth.
    pub size_start: f32,
    /// Billboard half-size at death.  Use `0.0` to shrink out.
    pub size_end: f32,
    /// Elapsed lifetime in seconds.
    pub age: f32,
    /// Total lifetime in seconds.
    pub lifetime: f32,
    pub(crate) active: bool,
}

impl Particle {
    /// Normalised age: `0.0` at birth → `1.0` at death.
    #[inline]
    pub fn t(&self) -> f32 {
        if self.lifetime > 0.0 {
            (self.age / self.lifetime).clamp(0.0, 1.0)
        } else {
            1.0
        }
    }

    /// Current interpolated colour.
    #[inline]
    pub fn color(&self) -> Rgb565 {
        let t = self.t();
        let r = lerp_ch(self.color_start.r(), self.color_end.r(), t, 31);
        let g = lerp_ch(self.color_start.g(), self.color_end.g(), t, 63);
        let b = lerp_ch(self.color_start.b(), self.color_end.b(), t, 31);
        Rgb565::new(r, g, b)
    }

    /// Current interpolated size.
    #[inline]
    pub fn size(&self) -> f32 {
        self.size_start + self.t() * (self.size_end - self.size_start)
    }

    /// Sample color using a multi-stop [`ColorGradient`][crate::color_gradient::ColorGradient].
    #[inline]
    pub fn color_with_gradient(
        &self,
        gradient: &crate::color_gradient::ColorGradient<Rgb565>,
    ) -> Rgb565 {
        gradient.sample(self.t())
    }

    /// Sample size using a parametric [`Curve`][crate::curve::Curve].
    #[inline]
    pub fn size_with_curve(&self, curve: &crate::curve::Curve<f32>) -> f32 {
        curve.sample(self.t())
    }
}

#[inline]
fn lerp_ch(start: u8, end: u8, t: f32, max: u8) -> u8 {
    (start as f32 + t * (end as f32 - start as f32)).clamp(0.0, max as f32) as u8
}

/// Parameters for spawning a single particle.
#[derive(Clone, Copy)]
pub struct ParticleSpawn {
    /// Initial world-space position.
    pub position: Point3<f32>,
    /// Initial velocity (world units/second).
    pub velocity: Vector3<f32>,
    /// Per-particle constant acceleration (added to gravity in `update`).
    pub acceleration: Vector3<f32>,
    /// Colour at birth.
    pub color_start: Rgb565,
    /// Colour at death.
    pub color_end: Rgb565,
    /// Billboard size at birth.
    pub size_start: f32,
    /// Billboard size at death.
    pub size_end: f32,
    /// Lifetime in seconds.
    pub lifetime: f32,
}

/// Fixed-capacity particle system.
///
/// `N` is the maximum number of simultaneously live particles.  Slots are
/// reused in-place so spawning never allocates.
pub struct ParticleSystem<const N: usize> {
    slots: [Particle; N],
    active: usize,
}

impl<const N: usize> ParticleSystem<N> {
    /// Create a new, empty system.
    pub fn new() -> Self {
        Self {
            slots: core::array::from_fn(|_| Particle {
                position: Point3::new(0.0, 0.0, 0.0),
                velocity: Vector3::new(0.0, 0.0, 0.0),
                acceleration: Vector3::new(0.0, 0.0, 0.0),
                color_start: Rgb565::new(0, 0, 0),
                color_end: Rgb565::new(0, 0, 0),
                size_start: 0.0,
                size_end: 0.0,
                age: 0.0,
                lifetime: 0.0,
                active: false,
            }),
            active: 0,
        }
    }

    /// Spawn a particle.  Returns `true` on success, `false` if the pool is
    /// at capacity (`N` particles already live).
    pub fn spawn(&mut self, s: ParticleSpawn) -> bool {
        for slot in &mut self.slots {
            if !slot.active {
                *slot = Particle {
                    position: s.position,
                    velocity: s.velocity,
                    acceleration: s.acceleration,
                    color_start: s.color_start,
                    color_end: s.color_end,
                    size_start: s.size_start,
                    size_end: s.size_end,
                    age: 0.0,
                    lifetime: s.lifetime,
                    active: true,
                };
                self.active += 1;
                return true;
            }
        }
        false
    }

    /// Advance all particles by `dt` seconds.
    ///
    /// `gravity` is applied uniformly to every particle's velocity.  Pass
    /// `Vector3::zeros()` to disable gravity for this system.
    pub fn update(&mut self, dt: f32, gravity: Vector3<f32>) {
        let mut live = 0usize;
        for slot in &mut self.slots {
            if !slot.active {
                continue;
            }
            slot.velocity += (slot.acceleration + gravity) * dt;
            slot.position += slot.velocity * dt;
            slot.age += dt;
            if slot.age >= slot.lifetime {
                slot.active = false;
            } else {
                live += 1;
            }
        }
        self.active = live;
    }

    /// Number of currently live particles.
    #[inline]
    pub fn active_count(&self) -> usize {
        self.active
    }

    /// `true` if no particles are live.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.active == 0
    }

    /// Iterate over live particles (read-only).
    pub fn iter_active(&self) -> impl Iterator<Item = &Particle> {
        self.slots.iter().filter(|p| p.active)
    }

    /// Record all live particles as camera-facing billboard quads into
    /// `commands`.
    ///
    /// Each particle emits two
    /// [`DrawPrimitive::ColoredTriangleWithDepth`][crate::primitive::DrawPrimitive::ColoredTriangleWithDepth]
    /// commands.  Billboard orientation uses world-up `(0, 1, 0)`, which is
    /// correct for all but extreme pitch angles.
    ///
    /// Returns the number of particles successfully projected and emitted.
    /// Particles that project behind the camera or outside the frustum are
    /// silently skipped.
    pub fn record<const MAX: usize>(
        &self,
        engine: &crate::engine::K3dengine,
        commands: &mut crate::command_buffer::CommandBuffer<MAX>,
    ) -> usize {
        use crate::command_buffer::RenderCommand;

        if self.active == 0 {
            return 0;
        }

        let camera_up = Vector3::new(0.0, 1.0, 0.0);
        let vp = engine.camera.vp_matrix;
        let mut emitted = 0usize;

        for particle in self.iter_active() {
            let size = particle.size();
            if size <= 0.0 {
                continue;
            }
            let color = particle.color();

            let billboard = Billboard::new(particle.position, size, color);
            let quad = billboard.generate_quad(engine.camera.position, camera_up);

            // Triangle 1: bottom-left (0), bottom-right (1), top-right (2)
            let Some((pts1, _)) = engine.transform_points_with_w(&[0usize, 1, 2], &quad, vp) else {
                continue;
            };

            // Triangle 2: bottom-left (0), top-right (2), top-left (3)
            let Some((pts2, _)) = engine.transform_points_with_w(&[0usize, 2, 3], &quad, vp) else {
                continue;
            };

            let _ = commands.push(RenderCommand::Draw(
                crate::primitive::DrawPrimitive::ColoredTriangleWithDepth {
                    points: [pts1[0].xy(), pts1[1].xy(), pts1[2].xy()],
                    depths: [pts1[0].z as f32, pts1[1].z as f32, pts1[2].z as f32],
                    color,
                },
            ));
            let _ = commands.push(RenderCommand::Draw(
                crate::primitive::DrawPrimitive::ColoredTriangleWithDepth {
                    points: [pts2[0].xy(), pts2[1].xy(), pts2[2].xy()],
                    depths: [pts2[0].z as f32, pts2[1].z as f32, pts2[2].z as f32],
                    color,
                },
            ));
            emitted += 1;
        }

        emitted
    }

    /// Record all live particles with an optional [`ColorGradient`][crate::color_gradient::ColorGradient]
    /// and/or [`Curve`][crate::curve::Curve] for size ramp.
    pub fn record_with_gradient<const MAX: usize>(
        &self,
        engine: &crate::engine::K3dengine,
        commands: &mut crate::command_buffer::CommandBuffer<MAX>,
        gradient: Option<&crate::color_gradient::ColorGradient<Rgb565>>,
        size_curve: Option<&crate::curve::Curve<f32>>,
    ) -> usize {
        use crate::command_buffer::RenderCommand;

        if self.active == 0 {
            return 0;
        }

        let camera_up = Vector3::new(0.0, 1.0, 0.0);
        let vp = engine.camera.vp_matrix;
        let mut emitted = 0usize;

        for particle in self.iter_active() {
            let size = if let Some(curve) = size_curve {
                particle.size_with_curve(curve)
            } else {
                particle.size()
            };
            if size <= 0.0 {
                continue;
            }

            let color = if let Some(grad) = gradient {
                particle.color_with_gradient(grad)
            } else {
                particle.color()
            };

            let billboard = Billboard::new(particle.position, size, color);
            let quad = billboard.generate_quad(engine.camera.position, camera_up);

            // Triangle 1: bottom-left (0), bottom-right (1), top-right (2)
            let Some((pts1, _)) = engine.transform_points_with_w(&[0usize, 1, 2], &quad, vp) else {
                continue;
            };

            // Triangle 2: bottom-left (0), top-right (2), top-left (3)
            let Some((pts2, _)) = engine.transform_points_with_w(&[0usize, 2, 3], &quad, vp) else {
                continue;
            };

            let _ = commands.push(RenderCommand::Draw(
                crate::primitive::DrawPrimitive::ColoredTriangleWithDepth {
                    points: [pts1[0].xy(), pts1[1].xy(), pts1[2].xy()],
                    depths: [pts1[0].z as f32, pts1[1].z as f32, pts1[2].z as f32],
                    color,
                },
            ));
            let _ = commands.push(RenderCommand::Draw(
                crate::primitive::DrawPrimitive::ColoredTriangleWithDepth {
                    points: [pts2[0].xy(), pts2[1].xy(), pts2[2].xy()],
                    depths: [pts2[0].z as f32, pts2[1].z as f32, pts2[2].z as f32],
                    color,
                },
            ));
            emitted += 1;
        }

        emitted
    }
}

impl<const N: usize> Default for ParticleSystem<N> {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    extern crate std;
    use super::*;
    use embedded_graphics_core::pixelcolor::WebColors;

    fn default_spawn(lifetime: f32) -> ParticleSpawn {
        ParticleSpawn {
            position: Point3::new(0.0, 0.0, 0.0),
            velocity: Vector3::new(0.0, 1.0, 0.0),
            acceleration: Vector3::zeros(),
            color_start: Rgb565::CSS_RED,
            color_end: Rgb565::CSS_BLUE,
            size_start: 1.0,
            size_end: 0.0,
            lifetime,
        }
    }

    #[test]
    fn test_spawn_increments_count() {
        let mut sys: ParticleSystem<4> = ParticleSystem::new();
        assert_eq!(sys.active_count(), 0);
        assert!(sys.spawn(default_spawn(2.0)));
        assert_eq!(sys.active_count(), 1);
    }

    #[test]
    fn test_pool_full_returns_false() {
        let mut sys: ParticleSystem<2> = ParticleSystem::new();
        assert!(sys.spawn(default_spawn(2.0)));
        assert!(sys.spawn(default_spawn(2.0)));
        assert!(!sys.spawn(default_spawn(2.0)));
    }

    #[test]
    fn test_update_kills_expired_particles() {
        let mut sys: ParticleSystem<4> = ParticleSystem::new();
        sys.spawn(default_spawn(0.1));
        sys.update(0.2, Vector3::zeros());
        assert_eq!(sys.active_count(), 0);
    }

    #[test]
    fn test_update_moves_particle_with_gravity() {
        let mut sys: ParticleSystem<4> = ParticleSystem::new();
        sys.spawn(default_spawn(5.0));
        let y0 = sys.iter_active().next().unwrap().position.y;
        sys.update(0.1, Vector3::new(0.0, -9.81, 0.0));
        let y1 = sys.iter_active().next().unwrap().position.y;
        // Gravity slows the upward velocity but initial velocity dominates briefly
        assert!(y1 != y0);
    }

    #[test]
    fn test_slot_reused_after_expiry() {
        let mut sys: ParticleSystem<1> = ParticleSystem::new();
        assert!(sys.spawn(default_spawn(0.05)));
        sys.update(0.1, Vector3::zeros());
        assert_eq!(sys.active_count(), 0);
        assert!(sys.spawn(default_spawn(2.0)));
        assert_eq!(sys.active_count(), 1);
    }

    #[test]
    fn test_color_at_birth_equals_start() {
        let mut sys: ParticleSystem<4> = ParticleSystem::new();
        sys.spawn(default_spawn(2.0));
        let p = sys.iter_active().next().unwrap();
        assert_eq!(p.t(), 0.0);
        assert_eq!(p.color(), Rgb565::CSS_RED);
    }

    #[test]
    fn test_size_shrinks_over_time() {
        let mut sys: ParticleSystem<4> = ParticleSystem::new();
        sys.spawn(default_spawn(2.0));
        let s0 = sys.iter_active().next().unwrap().size();
        sys.update(1.0, Vector3::zeros());
        let s1 = sys.iter_active().next().unwrap().size();
        assert!(s1 < s0);
    }

    #[test]
    fn test_empty_and_default() {
        let mut sys: ParticleSystem<4> = ParticleSystem::default();
        assert!(sys.is_empty());
        assert_eq!(sys.active_count(), 0);
        assert!(sys.spawn(default_spawn(1.0)));
        assert!(!sys.is_empty());
    }

    #[test]
    fn test_size_curve_and_color_gradient() {
        use crate::color_gradient::{ColorGradient, GradientStop};
        use crate::curve::{Curve, CurveInterpolation, CurveKey};

        let mut sys: ParticleSystem<2> = ParticleSystem::new();
        sys.spawn(default_spawn(2.0));
        let p = sys.iter_active().next().unwrap();

        let curve_keys = [
            CurveKey::new(0.0, 10.0, CurveInterpolation::Linear),
            CurveKey::new(1.0, 20.0, CurveInterpolation::Linear),
        ];
        let curve = Curve::new(&curve_keys);
        assert_eq!(p.size_with_curve(&curve), 10.0);

        let stops = [
            GradientStop::new(0.0, Rgb565::CSS_RED),
            GradientStop::new(1.0, Rgb565::CSS_BLUE),
        ];
        let grad = ColorGradient::new(&stops);
        assert_eq!(p.color_with_gradient(&grad), Rgb565::CSS_RED);
    }

    #[test]
    fn test_record_particles() {
        use crate::color_gradient::{ColorGradient, GradientStop};
        use crate::curve::{Curve, CurveInterpolation, CurveKey};

        let mut sys: ParticleSystem<4> = ParticleSystem::new();
        let mut spawn = default_spawn(2.0);
        spawn.position = Point3::new(0.0, 0.0, 5.0);
        sys.spawn(spawn);

        let mut engine = crate::engine::K3dengine::new(320, 240);
        engine.camera.set_position(Point3::new(0.0, 0.0, 0.0));
        engine.camera.set_target(Point3::new(0.0, 0.0, 5.0));

        let mut commands: crate::command_buffer::CommandBuffer<16> =
            crate::command_buffer::CommandBuffer::new();
        let emitted = sys.record(&engine, &mut commands);
        assert!(emitted > 0);
        assert!(!commands.is_empty());

        let mut commands_grad: crate::command_buffer::CommandBuffer<16> =
            crate::command_buffer::CommandBuffer::new();
        let curve_keys = [
            CurveKey::new(0.0, 1.0, CurveInterpolation::Linear),
            CurveKey::new(1.0, 0.5, CurveInterpolation::Linear),
        ];
        let curve = Curve::new(&curve_keys);
        let stops = [
            GradientStop::new(0.0, Rgb565::CSS_RED),
            GradientStop::new(1.0, Rgb565::CSS_GREEN),
        ];
        let grad = ColorGradient::new(&stops);

        let emitted_grad =
            sys.record_with_gradient(&engine, &mut commands_grad, Some(&grad), Some(&curve));
        assert!(emitted_grad > 0);
        assert!(!commands_grad.is_empty());
    }
}